ios - 在 Swift 3.0 中类型转换

标签 ios swift3 option-type

我在 Swift 3.0 迁移指南中找不到有关类型转换更改的任何信息。但是,我偶然发现了一些问题。

考虑这个 Playground :(顺便说一句,它不能在 Swift 的 Xcode 7.3.1 版本中编译)

var data1: AnyObject?
var data2: AnyObject?
var data3: AnyObject?

var tmpAny: Any?
var tmpString = "Hello!"

tmpAny = tmpString

data1 = tmpAny as AnyObject
data2 = tmpAny as AnyObject?
data3 = tmpAny as? AnyObject // Warning "Conditional cast from 'Any?' to 'AnyObject' always succeeds

print(type(of: data1))
print(type(of: data1!))

print()

print(type(of: data2))
print(type(of: data2!))

print()

print(type(of: data3))
print(type(of: data3!))

它打印:

Optional<AnyObject>
_SwiftValue

Optional<AnyObject>
_NSContiguousString

Optional<AnyObject>
_SwiftValue

在 Swift 3.0 中。

主要是,tmpAny as AnyObjecttmpAny as AnyObject 有什么区别?

最佳答案

类型转换:

switch data1 {
    case 0 as Int: 
    // use 'as' operator if you want to to discover the specific type of a constant or variable that is known only to be of type Any or AnyObject.
}

Swift 1.2 及更高版本中,as 只能用于向上转型(或消除歧义)和模式匹配。 Upcasting 意味着 guaranteed casting,意味着它会成功转换)。

data1 as AnyObject? 
// means that it's an Optional Value, it may either contain an AnyObject or it may be nil

data2 = tmpAny is AnyObject // when used 'is', data2 will be true if the instance is of that subclass type and false if it is not

沮丧:

由于向下转换可能会失败,类型转换可以用 ?! 标记。

data3 = tmpAny as? AnyObject 
// returns optional value of the type you are trying to downcast to
// do this if you're not sure if it succeeds
// if data3 couldn't be AnyObject, it would assign nil to the optional 
// means when you don't know what you're downcasting, you are assuming that it is Any, but it might be AnyObject, Integer or Float...
// that's why compiler warns - casting from 'Any?' to 'AnyObject' always succeeds

data4 = tmpAny as! AnyObject 
// attempts to downcast and force-unwraps the result after, as well
// do this if you're sure it succeeds, otherwise it will cause a runtime error if a wrong class/type is set

关于ios - 在 Swift 3.0 中类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611040/

相关文章:

ios - prepareForSegue 函数不起作用

swift - MIDIThruConnectionCreate 总是通过连接创建持久的 MIDI?

swift - 仅当变量的当前值非 nil 时才更改 Swift

java - Maven - 如何仅使用编译类路径的依赖项?

ios - Storyboard不包含带有标识符的 View Controller

iphone - UISegmentedControl 未重绘

ios - 在这里我无法显示从json解析得到的数据?

swift - Map 和 flatMap 在 Swift 1.2 中可选展开的区别

iphone - 如何在 iOS 5 中更改 UITabBarItem 中的文本颜色

ios - Swift 3 - 为什么我的导航栏不显示?