We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
泛型可以减少重复代码,是一种抽象的表达方式。where 关键字可以对泛型做约束。
func fn<T>(p: T) -> [T] { var r = [T]() r.append(p) return r } print(fn(p: "one")) // 结构体 struct S1<T> { var arr = [T]() mutating func add(_ p: T) { arr.append(p) } } var s1 = S1(arr: ["zero"]) s1.add("one") s1.add("two") print(s1.arr) // ["zero", "one", "two"]
关联类型
protocol pc { associatedtype T mutating func add(_ p: T) } struct S2: pc { typealias T = String // 类型推导,可省略 var strs = [String]() mutating func add(_ p: String) { strs.append(p) } }
泛型适用于嵌套类型
struct S3<T> { struct S4 { var p: T } var p1: T var p2: S4 } let s2 = S3(p1: 1, p2: S3.S4(p: 3)) let s3 = S3(p1: "one", p2: S3.S4(p: "three")) print(s2,s3)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
泛型可以减少重复代码,是一种抽象的表达方式。where 关键字可以对泛型做约束。
关联类型
泛型适用于嵌套类型
The text was updated successfully, but these errors were encountered: