【问题标题】:Casting in Swift 3.0Swift 3.0 中的铸造
【发布时间】:2016-09-21 08:16:08
【问题描述】:

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

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

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?有什么区别?

【问题讨论】:

  • 只需更改它:tmpAny as AnyObject 和警告消失

标签: ios swift3 optional


【解决方案1】:

选角

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 表示保证施法,即会施法成功)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多