Swift學習——A Swift Tour 協議和擴展
阿新 • • 發佈:2019-04-05
idt implement generics tail comm err com hidden data
版權聲明:本文為博主原創文章,未經博主同意不得轉載。 https://blog.csdn.net/zhenyu5211314/article/details/28854395
類。枚舉和結構體都能夠實現協議
在結構體中須要使用 mutating keyword來標記實現的協議方法,在類中不須要這個keyword
能夠使用協議的名稱作為數據類型(具體怎麽用。沒看明確。能夠看官方英文版)
也能夠在類。枚舉,結構體中使用泛型
有的時候須要對函數的參數類型進行具體的定義。對泛型實現某個接口。繼承自某個特定類型。兩個泛型屬於同一個類型等要求,使用? where keyword進行定義
假設條件簡單,還能夠簡化寫,比方<T: Equatable>和“<T where T: Equatable>是一樣的
Protocols and Extensions
Protocols? 協議的使用
使用keyword protocol 定義一個協議
protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }
類。枚舉和結構體都能夠實現協議
class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription
在結構體中須要使用 mutating keyword來標記實現的協議方法,在類中不須要這個keyword
協議基本的使用場合:
1. 須要由別的類實現的方法
2. 聲明位置類的接口
3. 兩個類之間通信
Extensions? 擴展的使用
能夠使用 extension keyword為一個類型拓展協議,添加方法和屬性
extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription
能夠使用協議的名稱作為數據類型(具體怎麽用。沒看明確。能夠看官方英文版)
let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
// protocolValue.anotherProperty // Uncomment to see the error
Generics?? 泛型的使用
使用?? < >? 聲明泛型函數或者泛型類型
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] {
var result = ItemType[]()
for i in 0..times {
result += item
}
return result
}
repeat("knock", 4)
也能夠在類。枚舉,結構體中使用泛型
// Reimplement the Swift standard library‘s optional type
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
有的時候須要對函數的參數類型進行具體的定義。對泛型實現某個接口。繼承自某個特定類型。兩個泛型屬於同一個類型等要求,使用? where keyword進行定義
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
假設條件簡單,還能夠簡化寫,比方<T: Equatable>和“<T where T: Equatable>是一樣的
入門就講到這,下一節我們說說 Language Guide
Swift學習——A Swift Tour 協議和擴展