Swift編程中的泛型解析
泛型代碼可以讓你寫出根據(jù)自我需求定義、適用于任何類型的,靈活且可重用的函數(shù)和類型。它可以讓你避免重復(fù)的代碼,用一種清晰和抽象的方式來表達(dá)代碼的意圖。
泛型是 Swift 強(qiáng)大特征中的其中一個(gè),許多 Swift 標(biāo)準(zhǔn)庫(kù)是通過泛型代碼構(gòu)建出來的。事實(shí)上,泛型的使用貫穿了整本語言手冊(cè),只是你沒有發(fā)現(xiàn)而已。例如,Swift 的數(shù)組和字典類型都是泛型集。你可以創(chuàng)建一個(gè)Int數(shù)組,也可創(chuàng)建一個(gè)String數(shù)組,或者甚至于可以是任何其他 Swift 的類型數(shù)據(jù)數(shù)組。同樣的,你也可以創(chuàng)建存儲(chǔ)任何指定類型的字典(dictionary),而且這些類型可以是沒有限制的。
泛型所解決的問題
這里是一個(gè)標(biāo)準(zhǔn)的,非泛型函數(shù)swapTwoInts,用來交換兩個(gè)Int值:
func swapTwoInts(inout a: Int, inout b: Int)
let temporaryA = a
a = b
b = temporaryA
}
這個(gè)函數(shù)使用寫入讀出(in-out)參數(shù)來交換a和b的值,請(qǐng)參考寫入讀出參數(shù)。
swapTwoInts函數(shù)可以交換b的原始值到a,也可以交換a的原始值到b,你可以調(diào)用這個(gè)函數(shù)交換兩個(gè)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函數(shù)是非常有用的,但是它只能交換Int值,如果你想要交換兩個(gè)String或者Double,就不得不寫更多的函數(shù),如 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函數(shù)功能都是相同的,唯一不同之處就在于傳入的變量類型不同,分別是Int、String和Double。
但實(shí)際應(yīng)用中通常需要一個(gè)用處更強(qiáng)大并且盡可能的考慮到更多的靈活性單個(gè)函數(shù),可以用來交換兩個(gè)任何類型值,很幸運(yùn)的是,泛型代碼幫你解決了這種問題。(一個(gè)這種泛型函數(shù)后面已經(jīng)定義好了。)
注意: 在所有三個(gè)函數(shù)中,a和b的類型是一樣的。如果a和b不是相同的類型,那它們倆就不能互換值。Swift 是類型安全的語言,所以它不允許一個(gè)String類型的變量和一個(gè)Double類型的變量互相交換值。如果一定要做,Swift 將報(bào)編譯錯(cuò)誤。
泛型函數(shù):類型參數(shù)
泛型函數(shù)可以訪問任何數(shù)據(jù)類型,如:'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)")
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
Before Swapping Int values are: 100 and 200 After Swapping Int values are: 200 and 100 Before Swapping String values are: Generics and Functions After Swapping String values are: Functions and Generics
函數(shù) exchange()用于交換其在上述方案中描述和<T>被用作類型參數(shù)值。這是第一次,函數(shù) exchange()被調(diào)用返回Int值,第二次調(diào)用函數(shù) exchange()將返回String值。多參數(shù)類型可包括用逗號(hào)分隔在尖括號(hào)內(nèi)。
類型參數(shù)被命名為用戶定義來了解擁有類型參數(shù)的目的。 Swift 提供<T>作為泛型類型參數(shù)的名字。 但是型像數(shù)組和字典參數(shù)也可以命名為鍵,值,以確定它們輸入屬于“字典”。
泛型類型
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()
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Type Parameters] [Swift, Generics, Type Parameters, Naming Type Parameters]
擴(kuò)展泛型類型
擴(kuò)展堆棧屬性要知道該項(xiàng)目的頂部包含在“extension” 關(guān)鍵字。
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).")
}
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Type Parameters] [Swift, Generics, Type Parameters, Naming Type Parameters]
在堆棧頂部的項(xiàng)目命名類型參數(shù)。
類型約束
Swift 語言允許“類型約束”指定類型參數(shù)是否從一個(gè)特定的類繼承,或者確保協(xié)議一致性標(biāo)準(zhǔn)。
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)")
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
Before Swapping Int values are: 100 and 200 After Swapping Int values are: 200 and 100 Before Swapping String values are: Generics and Functions After Swapping String values are: Functions and Generics
關(guān)聯(lián)類型
Swift 允許相關(guān)類型,并可由關(guān)鍵字“typealias”協(xié)議定義內(nèi)部聲明。
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)
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Type Parameters] [Swift, Generics, Type Parameters, Naming Type Parameters]
Where 子句
類型約束使用戶能夠定義與泛型函數(shù)或類型相關(guān)聯(lián)的類型的參數(shù)要求。用于定義相關(guān)類型的 'where' 子句聲明為類型參數(shù)列表的一部分要求。 “where”關(guān)鍵字類型參數(shù)后面類型和相關(guān)類型之間的相關(guān)類型的限制,平等關(guān)系的列表后放置。
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)
當(dāng)我們使用 playground 運(yùn)行上面的程序,得到以下結(jié)果
[Swift] [Swift, Generics] [Swift, Generics, Where Clause] [Swift, Generics, Where Clause]
相關(guān)文章
C語言 fseek(f,0,SEEK_SET)函數(shù)案例詳解
這篇文章主要介紹了C語言 fseek(f,0,SEEK_SET)函數(shù)案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08C++函數(shù)對(duì)象Functor與匿名函數(shù)對(duì)象Lambda表達(dá)式詳解
這篇文章主要介紹了C++函數(shù)對(duì)象Functor(仿函數(shù))與匿名函數(shù)對(duì)象(Lambda表達(dá)式)詳細(xì)介紹以及底層實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08C語言數(shù)據(jù)結(jié)構(gòu) 棧的基礎(chǔ)操作
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu) 棧的基礎(chǔ)操作的相關(guān)資料,需要的朋友可以參考下2017-05-05C++實(shí)現(xiàn)DES加密算法實(shí)例解析
這篇文章主要介紹了C++實(shí)現(xiàn)DES加密算法實(shí)例解析,是一個(gè)很實(shí)用的功能,需要的朋友可以參考下2014-08-08