美文网首页
(二十五)[Swift]Protocol的基本用法

(二十五)[Swift]Protocol的基本用法

作者: 修行猿 | 来源:发表于2016-08-21 08:59 被阅读152次

1.protocol中的方法参数不能有默认值

protocol Eatable {
    //func eat(foodName:String = "大米") //报错
    func eat(foodName:String) //正确
}

2.遵从protocol的class 或者 struct需要实现其中的方法,否则会报错

class Person:Eatable{
    func eat(foodName: String) {
        
    }
}
struct Pig:Eatable{
    func eat(foodName: String) {
        
    }
}

3.protocol中还可以声明变量,遵从的class必须有这样的变量或者getter setter方法

protocol Eatable{
    var foodName : String {get set}
    var eatMethod : String { get }
    func eat()
}
class Person : Eatable{
    var foodName: String = "大米"
    var eatMethod: String = "用嘴吃"
    func eat() {
        
    }
}

eatMethod 还可以这样实现

class Person : Eatable{
    private var innerEatMethod = "用嘴吃"
    var eatMethod: String {
        get {
            return innerEatMethod
        }
    }
    var foodName: String = "大米"
    func eat() {
        
    }
}

4.一个protocol可以继承另外一个protocol

protocol EatDrinkable : Eatable {
    var drinkMethod : String {get set}
    func drink()
}
class Person : EatDrinkable{
    var foodName: String = "上海记忆酸奶"
    var eatMethod: String = "用嘴吃"
    var drinkMethod: String = "用嘴喝"
    func eat() {
        
    }
    func drink() {
        
    }
}

5.一个类可以遵从多个协议

protocol Runable {
    func run ()
}
protocol Jumpable {
    func jump()
}
class Person : Runable,Jumpable{
    func jump() {
        
    }
    func run() {
        
    }
}

相关文章

  • (二十五)[Swift]Protocol的基本用法

    1.protocol中的方法参数不能有默认值 2.遵从protocol的class 或者 struct需要实现其中...

  • iOS Swift 协议的基本用法protocol

    简介 记录swift下协议的用法,与oc基本类似,基本一对一 1、定制协议 2、声明 3、使用 传输 4、遵守协...

  • Swift 协议

    前言 本篇文章主要讲解Swift中常用的协议Protocol,主要分析protocol的用法及底层存储结构。 一、...

  • 第五章、oc的语言中级阶段

    Day17.protocol协议和NSString字符串的用法 1,protocol基本概念 2,protocol...

  • Swift基础-02

    1.Swift中switch基本用法 关于 switch的特殊用法 2.Swift中区间 CountableRan...

  • Swift-11:protocol

    本文主要分析protocol的用法及底层存储结构 协议的基本用法 【语法格式】:协议的语法格式 class、str...

  • swift中的协议和扩展

    1.Swift中的Protocol 什么是Protocol? Protocol是Swift中的一种自定义类型,可以...

  • 基本语法

    swift基本语法 五种类型 枚举(enum),结构体(struct),类(class),协议(protocol)...

  • Swift 泛型和Protocol 用法

    简单的Protocol 范性用法,还可以针对复杂的扩展。 实战1: 用例:

  • Swift小知识

    1. 关于Swift中Protocol 1. 在 Swift 中,Delegate 就是基于 Protocol 实...

网友评论

      本文标题:(二十五)[Swift]Protocol的基本用法

      本文链接:https://www.haomeiwen.com/subject/xuoisttx.html