在Swift3中,您可以这样做吗?
func example<T>()->(T) where T can only be String or Int
或者,您仅需要两个扩展名吗?
例如,该函数计算数学函数。
输入在概念上是“数字”,但可以是法语字符串或整数。因此,输入可以是字符串“ cent”或整数100。结果将是平方根,即字符串“ dix”或整数10。
这不是泛型的工作。使用两种类型的静态集合并没有通用的方法。
这是使用枚举的理想情况:
enum SomeEnum { //TODO: name me
case string(String)
case int(Int)
}
func foo(input: SomeEnum) -> SomeEnum {
switch input {
case .string(let s):
print("This is a String: \(s)")
return(.string("abc"))
case .int(let i):
print("This is an Int: \(i)")
return(.int(123))
}
}
print(foo(input: SomeEnum.string("qwerty")))
print(foo(input: SomeEnum.int(5)))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句