nal*_*d88 30 generics ios swift
我试图找出如何为泛型类(在Swift中)实现类型约束,它将泛型类型仅限于数值类型.例如Double,Int等,但不是字符串.谢谢你的帮助.
Mar*_*don 28
您可以使用尖括号为泛型类(相同的语法适用于函数)指定类型约束(使用类和协议):
class Foo<T: Equatable, U: Comparable> { }
Run Code Online (Sandbox Code Playgroud)
要在单个类型上指定多个要求,请使用以下where子句:
class Foo<T: UIViewController where T: UITableViewDataSource, T: UITextFieldDelegate> { }
Run Code Online (Sandbox Code Playgroud)
然而,它并不像你可以指定一个泛型参数子句可选的要求,所以一个可能的解决方案是创建一个所有的数字类型通过扩展实现,然后限制对需求类的协议:
protocol Numeric { }
extension Float: Numeric {}
extension Double: Numeric {}
extension Int: Numeric {}
class NumberCruncher<C1: Numeric> {
func echo(num: C1)-> C1 {
return num
}
}
NumberCruncher<Int>().echo(42)
NumberCruncher<Float>().echo(3.14)
Run Code Online (Sandbox Code Playgroud)
DeF*_*enZ 12
Strideable是每种标准数字类型符合的最小标准协议,但它也有一些符合它的类型.
http://swiftdoc.org/protocol/Strideable/hierarchy/
或者你可以使用IntegerType和FloatingPointType.