2016-09-21 11 views
2

Swift 3.0移行ガイドの型キャストの変更については何も見つかりません。しかし、私はいくつかの発行につまずいた。 (BTW Xcodeでコンパイルにスイフトの7.3.1バージョンをdoesntの)Swift 3.0のキャスティング

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!)) 

それが印刷:スイフト3.0で

Optional<AnyObject> 
_SwiftValue 

Optional<AnyObject> 
_NSContiguousString 

Optional<AnyObject> 
_SwiftValue 

この遊び場を考えます。

主に、tmpAny as AnyObjecttmpAny as AnyObject?の違いは何ですか?

+0

単純に変更してください:** tmpAny AnyObject ** and Warning gone –

答えて

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. 
} 

1.2スウィフト以降でasのみアップキャスト(又は曖昧さ回避)とパターンマッチングのために使用することができます。 アップキャスティングは、キャスティングが保証されていることを意味します。つまり、キャストは成功します。ダウンキャスト

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