【问题标题】:Swift 2.0 Generics and Type Safety IssuesSwift 2.0 泛型和类型安全问题
【发布时间】:2016-01-18 13:23:31
【问题描述】:

我正在做这个教程http://blog.teamtreehouse.com/introduction-learn-power-swift-generics,我遇到了这段代码;

func someFunction<T, U>(a: T, b: U) {}

问题是当我调用函数时使用

someFunction<String, Int>(1, "Test") 

我收到一条错误消息,提示“无法显式特化泛型函数”。

然后我把它改成

someFunction(1,b: "Test")

现在没有错误了。问题是现在没有类型安全。 (代码有什么问题吗,因为它是在 swift 2.0 之前编写的?)重新引入类型安全的最佳方法是什么?

【问题讨论】:

  • 为什么你认为没有类型安全?
  • 因为我可以将任何类型放入 someFunction 参数中并且没有错误?
  • 能不能看看函数是怎么实现的?
  • 哦,我现在看到了......所以,使用你想要的任何类型作为这个函数的参数真的很安全。

标签: swift generics swift2 type-safety


【解决方案1】:

声明是完全通用的,并指定可以使用任何两种类型。

func someFunction<T, U>(a: T, b: U) {}

并不是说 Swift 没有类型安全,这就是你如何表达一个没有任何类型约束的泛型。

你得到你想要的。

如果你想将函数限制为 String 和 Int,你可以写成

func someFunction(a:String, b:Int)

泛型更常用于集合、协议和类。基本类型很少需要它们:

func someFunction<T:Comparable, U:Comparable>(a:T, b:U) -> Bool
{ return (a < b) || (a > b) }

【讨论】:

    【解决方案2】:

    好的,请参阅这个“自我解释”示例。在操场上试一试,玩一下。

    func foo<T>(t: T)->T {
        return t
    }
    
    // here the resulting type is infered by compiler
    let i = foo(1)       // 1
    let j: Int = foo(1)  // 1
    let t = foo("alpha") // "alpha"
    
    // if you declare it self ..
    //let s: String = foo(1) // error: cannot convert value of type 'Int' to expected argument type 'String'
    
    /* this fails to compile!
    func bar<T>(t:T)->Int {
        return t.count
    }
    */
    
    /* this fails to compile too !!
    func bar0<T:CollectionType>(t:T)->Int {
        return t.count
    }
    */
    
    func bar<T:CollectionType>(t:T)->T.Index.Distance {
        return t.count
    }
    
    let arr = [1,2,3]
    let k:Int = bar(arr) // 3
    print(k.dynamicType) // Int
    
    // and even more interesting
    let l = bar(arr)
    print(l.dynamicType) // Int
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      相关资源
      最近更新 更多