泛型 – 在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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...