【Swift 60秒】81 - Protocols

0x00 Lesson

Protocols are a way of describing what properties and methods something must have.You then tell Swift which types use that protocol - a process known as adopting or conforming to a protocol.

For example, we can write a function that accepts something with an id property, but we don’t care precisely what type of data is used. We’ll start by creating an Identifiable protocol, which will require all conforming types to have an id string that can be read (“get”) or written (“set”):

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

We can't create instances of that protocol - it’s a description of what we want, rather than something we can create and use directly. 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)")
}

0x01 我的小作品

欢迎体验我的作品之一:小编辑器-XCompiler
在线编辑器~小而巧
App Store 搜索即可~


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/128669583
今日推荐