泛型 – 在Swift中你可以将泛型约束为两种类型吗? String和Int

前端之家收集整理的这篇文章主要介绍了泛型 – 在Swift中你可以将泛型约束为两种类型吗? String和Int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Swift3中,你能做到这一点……
func example<T>()->(T) where T can only be String or Int

或者,你只需要两个扩展名吗?

例如,该函数计算数学函数.

输入在概念上是一个“数字”,但它可以是法语字符串,也可以是整数.因此输入可以是字符串“cent”或Int 100.结果将是平方根,因此字符串“dix”或Int 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)))

You can try it here

原文链接:https://www.f2er.com/swift/318594.html

猜你在找的Swift相关文章