Skip to content

Instantly share code, notes, and snippets.

@acalism
Created July 5, 2017 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalism/b4aec095b98ad76f6091db6efefb3d3b to your computer and use it in GitHub Desktop.
Save acalism/b4aec095b98ad76f6091db6efefb3d3b to your computer and use it in GitHub Desktop.
Swift 泛型特化
protocol MakeSelf {
init()
}
class MS: MakeSelf {
static let shared = MS()
required init() {
//
}
}
// 1. 参数是泛型
func show<T: MakeSelf>(_ obj: T) {
print(obj)
}
// 2. 仅返回值是泛型
func create<T: MakeSelf>() -> T {
return T()
}
// 3. closure 带泛型参数
func request<T: MakeSelf>(completion: (T)->Void) {
completion(T())
}
// 4. 将泛型参数写入方法参数和closure参数
func request<T: MakeSelf>(type: T.Type, completion: (T)->Void) {
completion(T())
}
// example
// 传入泛型参数,所以$0获得了类型MS————从后面的例子来看,type这个参数是可以省略的(指明closure参数的类型即可)
request(type: MS.self, completion: {
print($0)
})
// 指明closure参数的类型,所以整个函数也完成了特化
request(completion: { (t: MS) in
print(t)
})
// 指明返回值类型,从而完成函数的泛型特化
let ms: MS = create()
print(ms)
@acalism
Copy link
Author

acalism commented Jul 5, 2017

Swift泛型仅在定义时允许用<>,而使用时不能使用<>来指明泛型参数的类型。

@ArthurChi
Copy link

如果在编译期,将protocol类型替换成了指定类型,算不算特化?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment