如何在Swift中的函数内部使用协议?

时间:2020-02-25 20:10:53

标签: swift

我正在阅读一系列Swift教程,并且我不想在不了解这一点的情况下继续前进

protocol Identifiable {
    var id: String { get set }
}
/*:
 We can’t create instances of that protocol - it’s a description, not a type by itself.
 But we can create a struct that conforms to it:
 */
struct User: Identifiable {
    var id: String
}
//: Finally, we’ll write a `displayID()` function that accepts any `Identifiable` object:
func displayID(thing: Identifiable) {
    print("My ID is \(thing.id)")
}

这是tutorial page

说我现在要运行displayID并获得thing.id,那怎么办?

3 个答案:

答案 0 :(得分:1)

您可以在swift playgrounds上尝试使用它,例如,这是一种使用方法:

import Foundation

protocol Identifiable {
    var id: String { get set }
}

struct User: Identifiable {
    var id: String
}

class ViewController {
    func displayID(thing: Identifiable) {
        print("My ID is \(thing.id)")
    }
}

let vc = ViewController()
let user = User(id: "12")
vc.displayID(thing: user)
// My ID is 12

通常,协议被视为类似于要遵循的类或结构的契约(java / android中的接口),因此您知道使类或结构符合协议将确保您可以实现基本方法的实现将来需要这种对象/实例。

同样,它们的意思是允许您在自动化测试中提供示例实现的示例,以便获得模拟id,而不是本例中的真实ID。

答案 1 :(得分:0)

协议只是意味着...

您必须拥有所有陈述的东西!

这就是协议的全部内容!

这是您的协议

protocol Identifiable {
    var id: String { get set }
}

这意味着您必须有一个“ id”!

所以这个:

class Test: Identifiable {
}

错了!!!

但这是

class Test: Identifiable {
   var id: String
}

是正确的!

仅此而已!

协议就是这么简单!

答案 2 :(得分:0)

是的,确实不能创建协议实例。但是您可以创建实现协议的类和结构的实例。协议仅确保实现该协议的结构或类必须具有协议中定义的所有这些属性和方法。 您可以说议定书是合同。如果要实现,就需要实现。