如何在Swift中的函数内使用协议?
我正在学习一系列Swift教程,我不想在不理解这一点的情况下继续学习如何在Swift中的函数内使用协议?,swift,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:
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
并获取东西。id
,这将如何工作?您可以在上面尝试这是一种使用方法,例如:
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。协议只是意味着 你必须把所有的东西都说出来! 这就是协议的全部内容 这是你的协议
protocol Identifiable {
var id: String { get set }
}
这意味着你必须有一个“身份证”
因此:
class Test: Identifiable {
}
这是错误的!!!
但这是:
class Test: Identifiable {
var id: String
}
是正确的!!!
就这些
协议就是这么简单 是的,确实不能创建协议的实例。但您可以创建实现协议的类和结构的实例。协议只需确保实现该协议的结构或类必须具有协议中定义的所有这些属性和方法可以说协议是一种契约。如果你实现了它,你就需要实现它。不清楚你的要求是什么,因为你发布的代码已经实现了你的问题。@CraigSiemens,我猜OP只是想快速解释一下协议到底是什么-我为他做了什么@CraigSiemens想知道如何调用
displayID
,我从@denis\u lor那里得到了我需要的东西