泛型代碼可以讓你寫出根據自我需求定義、適用於任何類型的,靈活且可重用的函數和類型。它可以讓你避免重複的代碼,用一種清晰和抽象的方式來表達代碼的意圖。
泛型是 Swift 強大特徵中的其中一個,許多 Swift 標準庫是通過泛型代碼構建出來的。事實上,泛型的使用貫穿了整本語言手冊,只是你沒有發現而已。例如,Swift 的數組和字典類型都是泛型集。你可以建立一個Int數組,也可建立一個String數組,或者甚至於可以是任何其他 Swift 的類型資料數組。同樣的,你也可以建立儲存任何指定類型的字典(dictionary),而且這些類型可以是沒有限制的。
泛型所解決的問題
這裡是一個標準的,非泛型函數swapTwoInts,用來交換兩個Int值:
複製代碼 代碼如下:
func swapTwoInts(inout a: Int, inout b: Int)
let temporaryA = a
a = b
b = temporaryA
}
這個函數使用寫入讀出(in-out)參數來交換a和b的值,請參考寫入讀出參數。
swapTwoInts函數可以交換b的原始值到a,也可以交換a的原始值到b,你可以調用這個函數交換兩個Int變數值:
複製代碼 代碼如下:
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// 輸出 "someInt is now 107, and anotherInt is now 3"
swapTwoInts函數是非常有用的,但是它只能交換Int值,如果你想要交換兩個String或者Double,就不得不寫更多的函數,如 swapTwoStrings和swapTwoDoublesfunctions,如同如下所示:
func swapTwoStrings(inout a: String, inout b: String) {
let temporaryA = a
a = b
b = temporaryA
}
func swapTwoDoubles(inout a: Double, inout b: Double) {
let temporaryA = a
a = b
b = temporaryA
}
你可能注意到 swapTwoInts、 swapTwoStrings和swapTwoDoubles函數功能都是相同的,唯一不同之處就在於傳入的變數類型不同,分別是Int、String和Double。
但實際應用中通常需要一個用處更強大並且儘可能的考慮到更多的靈活性單個函數,可以用來交換兩個任何類型值,很幸運的是,泛型代碼幫你解決了這種問題。(一個這種泛型函數後面已經定義好了。)
注意: 在所有三個函數中,a和b的類型是一樣的。如果a和b不是相同的類型,那它們倆就不能互換值。Swift 是型別安全的語言,所以它不允許一個String類型的變數和一個Double類型的變數互相交換值。如果一定要做,Swift 將報編譯錯誤。
泛型函數:型別參數
泛型函數可以訪問任何資料類型,如:'Int' 或 'String'.
複製代碼 代碼如下:
func exchange<T>(inout a: T, inout b: T) {
let temp = a
a = b
b = temp
}
var numb1 = 100
var numb2 = 200
println("Before Swapping Int values are: \(numb1) and \(numb2)")
exchange(&numb1, &numb2)
println("After Swapping Int values are: \(numb1) and \(numb2)")
var str1 = "Generics"
var str2 = "Functions"
println("Before Swapping String values are: \(str1) and \(str2)")
exchange(&str1, &str2)
println("After Swapping String values are: \(str1) and \(str2)")
當我們使用 playground 運行上面的程式,得到以下結果
Before Swapping Int values are: 100 and 200After Swapping Int values are: 200 and 100Before Swapping String values are: Generics and FunctionsAfter Swapping String values are: Functions and Generics
函數 exchange()用於交換其在上述方案中描述和<T>被用作型別參數值。這是第一次,函數 exchange()被調用返回Int值,第二次調用函數 exchange()將返回String值。多參數類型可包括用逗號分隔在角括弧內。
型別參數被命名為使用者定義來瞭解擁有型別參數的目的。 Swift 提供<T>作為泛型型別參數的名字。 但是型像數組和字典參數也可以命名為鍵,值,以確定它們輸入屬於“字典”。
泛型型別
複製代碼 代碼如下:
struct TOS<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var tos = TOS<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Type Parameters")
println(tos.items)
tos.push("Naming Type Parameters")
println(tos.items)
let deletetos = tos.pop()
當我們使用 playground 運行上面的程式,得到以下結果
[Swift][Swift, Generics][Swift, Generics, Type Parameters][Swift, Generics, Type Parameters, Naming Type Parameters]
擴充泛型型別
擴充堆棧屬性要知道該項目的頂部包含在“extension” 關鍵字。
複製代碼 代碼如下:
struct TOS<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var tos = TOS<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Type Parameters")
println(tos.items)
tos.push("Naming Type Parameters")
println(tos.items)
extension TOS {
var first: T? {
return items.isEmpty ? nil : items[items.count - 1]
}
}
if let first = tos.first {
println("The top item on the stack is \(first).")
}
當我們使用 playground 運行上面的程式,得到以下結果
[Swift][Swift, Generics][Swift, Generics, Type Parameters][Swift, Generics, Type Parameters, Naming Type Parameters]
在堆棧頂部的項目命名型別參數。
類型約束
Swift 語言允許“類型約束”指定型別參數是否從一個特定的類繼承,或者確保協議一致性標準。
複製代碼 代碼如下:
func exchange<T>(inout a: T, inout b: T) {
let temp = a
a = b
b = temp
}
var numb1 = 100
var numb2 = 200
println("Before Swapping Int values are: \(numb1) and \(numb2)")
exchange(&numb1, &numb2)
println("After Swapping Int values are: \(numb1) and \(numb2)")
var str1 = "Generics"
var str2 = "Functions"
println("Before Swapping String values are: \(str1) and \(str2)")
exchange(&str1, &str2)
println("After Swapping String values are: \(str1) and \(str2)")
當我們使用 playground 運行上面的程式,得到以下結果
Before Swapping Int values are: 100 and 200After Swapping Int values are: 200 and 100Before Swapping String values are: Generics and FunctionsAfter Swapping String values are: Functions and Generics
關聯類別型
Swift 允許相互關聯類型,並可由關鍵字“typealias”協議定義內部聲明。
複製代碼 代碼如下:
protocol Container {
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct TOS<T>: Container {
// original Stack<T> implementation
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
var tos = TOS<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Type Parameters")
println(tos.items)
tos.push("Naming Type Parameters")
println(tos.items)
當我們使用 playground 運行上面的程式,得到以下結果
[Swift][Swift, Generics][Swift, Generics, Type Parameters][Swift, Generics, Type Parameters, Naming Type Parameters]
Where 子句
類型約束使使用者能夠定義與泛型函數或類型相關聯的類型的參數要求。用於定義相互關聯類型的 'where' 子句聲明為型別參數列表的一部分要求。 “where”關鍵字型別參數後面類型和相互關聯類型之間的相互關聯類型的限制,平等關係的列表後放置。
複製代碼 代碼如下:
protocol Container {
typealias ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct Stack<T>: Container {
// original Stack<T> implementation
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
// conformance to the Container protocol
mutating func append(item: T) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> T {
return items[i]
}
}
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
var tos = Stack<String>()
tos.push("Swift")
println(tos.items)
tos.push("Generics")
println(tos.items)
tos.push("Where Clause")
println(tos.items)
var eos = ["Swift", "Generics", "Where Clause"]
println(eos)
當我們使用 playground 運行上面的程式,得到以下結果
[Swift][Swift, Generics][Swift, Generics, Where Clause][Swift, Generics, Where Clause]