我正在学习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)")
}这是教程页
假设我现在想运行displayID并获得thing.id,这将如何工作?
发布于 2020-02-25 20:16:20
您可以在swift游乐场上试用它--这是您可以使用它的一种方法,例如:
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,如本例所示。
发布于 2020-02-25 20:21:56
协议只是意味着..。
你一定把所有的东西都写好了!
这就是所有的协议!
这是你的协议
protocol Identifiable {
var id: String { get set }
}这意味着你必须有一个“身份”!
所以这个:
class Test: Identifiable {
}错了!
但这一点:
class Test: Identifiable {
var id: String
}是正确的!!
仅此而已!
协议就这么简单!
发布于 2020-02-25 20:29:18
是的,确实不能创建协议的实例。但是您可以创建实现协议的类和结构的实例。协议只需确保实现此协议的结构或类必须具有协议中定义的所有这些属性和方法。,您可以说协议是一个合同。如果您实现了它,就需要完成它。
https://stackoverflow.com/questions/60402429
复制相似问题