2016-09-21 2 views
2

Swift 3.0 마이그레이션 가이드에서 유형 변환의 변경 사항을 찾을 수 없습니다. 그러나, 나는 발행 된 것을 우연히 만났다. (BTW 엑스 코드 컴파일에게 스위프트의 7.3.1 버전을 나던)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

** 단순히 Anybody **로 변경하고 경고는 사라졌습니다. –

답변

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 이상에서, asupcasting (또는 동음) 및 패턴 매칭에 사용될 수있다. 업 캐스팅은 보장 된 캐스팅을 의미합니다. 즉, 캐스팅이 성공적으로 수행되었음을 의미합니다. Downcasting

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 

는 :

downcasting 실패 할 수 있기 때문에, 캐스팅 타입 또는 ?!로 표시 될 수있다.

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