import foundation
func swaptwoints(inout a: int, inout b: int)
func swaptwostrings(inout a: string, inout b: string)
func swaptwodoubles(inout a: double, inout b: double)
//泛型**可以讓你寫出根據自我需求定義適用於任何型別的,靈活且可重用的函式和型別。它可以讓你避免重複**,用一種清晰和抽象的方式來表達**的意圖
//t為佔位型別名字,可支援多個型別引數,命名在尖括號中,用逗號分開
func swaptwovalues(inout a: t, inout b: t)
var someint = 3
var anotherint = 107
swaptwovalues(&someint, b: &anotherint)
var somestring = "hello"
var anotherstring = "world"
swaptwovalues(&somestring, b: &anotherstring)
//mark: - 泛型型別與泛型引數
struct intstack
mutating func pop() -> int
}struct stack
mutating func pop() -> t
}var stackofstrings = stack()
stackofstrings.push("uno")
stackofstrings.push("dos")
stackofstrings.push("tres")
stackofstrings.push("cuatro")
// 現在棧已經有4個string了
let fromthetop = stackofstrings.pop()
//mark: - 型別約束
//型別約束指定了乙個必須繼承自指定類的型別引數,或者遵循乙個特定的協議或協議構成
/*//第乙個型別引數t,有乙個需要t必須是someclass子類的型別約束;第二個型別引數u,有乙個需要u必須遵循someprotocol協議的型別約束
func somefunction(somet: t, someu: u)
*/func findstringindex(array: [string], valuetofind: string) -> int?
}return nil
}let strings = ["cat", "dog", "llama", "parakeet", "terrapin"]
if let foundindex = findstringindex(strings, valuetofind: "llama")
// 輸出 "the index of llama is 2"
//swift 標準庫中定義了乙個equatable協議,該協議要求任何遵循的型別實現等式符(==)和不等符(!=)對任何兩個該型別進行比較。所有的 swift 標準型別自動支援equatable協議。
func findindex(array: [t], valuetofind: t) -> int?
}return nil
}let doubleindex = findindex([3.14159, 0.1, 0.25], valuetofind: 9.3)
// doubleindex is an optional int with no value, because 9.3 is not in the array
let stringindex = findindex(["mike", "malcolm", "andrea"], valuetofind: "andrea")
// stringindex is an optional int containing a value of 2
泛型程式設計之泛型引數
問題 用c 語言實現求乙個數的平方。分析 乙個數,可以是int double complex等,規則求數的平方 x x 偽 sqrt x return x x 實現一 提供一組用於求不同數字型別的平方函式。int sqrtint int x int sqrtdouble double x 實現二 上...
泛型之泛型類
public class a 構造引數型別上使用泛型 public a t t 方法返回值上使用泛型 public t gett 方法的引數上使用泛型 這是泛型類的方法,而不是泛型方法 public void sett t t 方法的返回值和引數型別上使用泛型 public t foo t t pu...
泛型之泛型類
public class a 構造引數型別上使用泛型 public a t t 方法返回值上使用泛型 public t gett 方法的引數上使用泛型 這是泛型類的方法,而不是泛型方法 public void sett t t 方法的返回值和引數型別上使用泛型 public t foo t t pu...