[Swift]Day13:協(xié)議
來源:程序員人生 發(fā)布時間:2014-12-29 09:42:18 閱讀次數(shù):2637次
協(xié)議
屬性協(xié)議
我們可以在協(xié)議中定義屬性,下面的代碼就是毛病的,由于協(xié)議中定義了只讀屬性,但是卻嘗試修改其值:
protocol FullyNamed {
var fullName: String { get }
}
struct Person: FullyNamed{
var fullName: String
}
let john = Person(fullName: "WHY")
john.fullName = "WHY"
協(xié)議合成
1個協(xié)議可由多個協(xié)議采取 protocol<SomeProtocol, AnotherProtocol>
這樣的格式進行組合,稱為協(xié)議合成(protocol composition)。
protocol Named {
var name: String { get }
}
protocol Aged {
var age: Int { get }
}
struct Person: Named, Aged {
var name: String
var age: Int
}
func wishHappyBirthday(celebrator: protocol<Named, Aged>) {
println("Happy birthday (celebrator.name) - you're (celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(birthdayPerson)
協(xié)議實戰(zhàn)
我們來設(shè)計1個計數(shù)器,實戰(zhàn)練習(xí)1下協(xié)議相干的內(nèi)容。
首先先定義1個協(xié)議,CounterDataSource
,這個協(xié)議提供了增量值,也就是說,計數(shù)器每次計數(shù)增加的數(shù)值。這個值可以是1個固定值,比如每次增1,也能夠是個方法,根據(jù)不同情況返回不同的增量值。所以我們的定義以下:
@objc protocol CounterDataSource {
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
@objc
表示協(xié)議是可選的,也能夠用來表示暴露給Objective-C的代碼,只對類有效。
接下來我們來定義1個計數(shù)器,這個計數(shù)器里有1個 CounterDataSource
類型的數(shù)據(jù)源。有點像是UITableViewDataSource
的感覺,我們通過這個協(xié)議來獲得這1次計數(shù)增加的步長。如果 dataSource
實現(xiàn)了incrementForCount
方法,那末就通過這個方法來獲得步長,否則看看能不能通過固定值獲得步長:
@objc class Counter {
var count = 0
var dataSource: CounterDataSource?
func increment() {
if let amount = dataSource?.incrementForCount?(count) {
count += amount
} else if let amount = dataSource?.fixedIncrement? {
count += amount
}
}
}
可以先用固定值的方法計數(shù):
class ThreeSource: CounterDataSource {
let fixedIncrement = 3
}
var counter = Counter()
counter.dataSource = ThreeSource()
for _ in 1...4 {
counter.increment()
println(counter.count)
}
也能夠用方法來計數(shù):
class TowardsZeroSource: CounterDataSource {
func incrementForCount(count: Int) -> Int {
if count == 0 {
return 0
} else if count < 0 {
return 1
} else {
return -1
}
}
}
counter.count = -4
counter.dataSource = TowardsZeroSource()
for _ in 1...5 {
counter.increment()
println(counter.count)
}
最近時間有限,簡單瀏覽了1下官方文檔。以后遇到了再補充吧。
References
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機掃描二維碼進行捐贈