【问题标题】:as! vs as operator in Xcode 6.3 in Swift作为! vs 作为 Swift 中 Xcode 6.3 中的运算符
【发布时间】:2015-04-16 12:39:17
【问题描述】:

Swift 在 Xcode 6.3 中发生了很大变化。我必须在我的每个应用程序as -> as! 中替换几十个位置。为什么,现在的规则是什么?

【问题讨论】:

标签: swift casting


【解决方案1】:

在 Swift 1.2 之前,as 运算符可用于执行两种不同类型的转换,具体取决于要转换的表达式的类型和要转换的类型:

  • 保证将一种类型的值转换为另一种类型的值,其成功可以由 Swift 编译器验证。例如,向上转换(即,从一个类转换为其超类之一)或指定文字表达式的类型(例如,1 为浮点数)。

  • 强制转换一个值到另一个值,Swift 编译器无法保证其安全性,并且可能导致运行时陷阱。例如向下转换,从一个类转换为其子类之一。

Swift 1.2 将保证转换和强制转换的概念分离为两个不同的运算符。保证转换仍使用as 运算符执行,但强制转换现在使用as! 运算符。 ! 表示转换可能会失败。这样,您一眼就知道哪些转换可能导致程序崩溃。

来源:https://developer.apple.com/swift/blog/?id=23

【讨论】:

    【解决方案2】:

    实际区别是这样的:

    var optionalString = dict.objectForKey("SomeKey") as? String
    

    optionalString 将是String? 类型的变量。如果基础类型不是String,这将无害地将nil 分配给可选。

    var optionalString = dict.objectForKey("SomeKey") as! String?
    

    这表示,我知道这东西是String?。这也将导致optionalString 的类型为String?,但如果基础类型是其他类型,它将崩溃。

    然后将第一个样式与if let 一起使用以安全地解开可选:

    if let string = dict.objectForKey("SomeKey") as? String {
        // If I get here, I know that "SomeKey" is a valid key in the dictionary, I correctly
        // identified the type as String, and the value is now unwrapped and ready to use.  In
        // this case "string" has the type "String".
        println(string)
    }
    

    【讨论】:

    【解决方案3】:

    根据release notes

    保证转换和“强制失败”转换的概念 现在分为两个运算符。现在强制失败转换 使用 as!操作员。这 !让代码的读者清楚地知道 强制转换可能会失败并产生运行时错误。 “as”运算符 仍然用于向上转换(例如“someDerivedValue as Base”)和类型 保证永远不会失败的注释(“0 as Int8”)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2012-04-02
      • 1970-01-01
      相关资源
      最近更新 更多