앱을 swift3로 변환하고 다음과 같은 문제가 발생합니다.
@objc required init(response: HTTPURLResponse, representation: [NSObject : AnyObject])
{
if (representation.value(forKeyPath: "title") is String) {
self.title = **representation.value**(forKeyPath: "title") as! String
}
다음과 같은 오류가 발생합니다.
[NSObject : AnyObject] 유형의 값에는 멤버 값이 없습니다.
이전 버전의 코드에서는 AnyObject를 표현 유형으로 사용했지만 그렇게하면 오류 AnyObject is not a subtype of NSObject
가 발생 합니다.
if (representation.value(forKeyPath: "foo") is String) {
let elementObj = Element(response: response, representation:**representation.value(forKeyPath: "foo")**!)
}
Objective-C와 Swift 스타일을 혼합하고 있습니다. 실제로 결정하는 것이 좋습니다.
다시 브리징 NSDictionary
은 자동이 아닙니다.
중히 여기다:
let y: [NSObject: AnyObject] = ["foo" as NSString: 3 as AnyObject] // this is awkward, mixing Swift Dictionary with explicit types yet using an Obj-C type inside
let z: NSDictionary = ["foo": 3]
(y as NSDictionary).value(forKeyPath: "foo") // 3
// y["foo"] // error, y's keys are explicitly typed as NSObject; reverse bridging String -> NSObject/NSString is not automatic
y["foo" as NSString] // 3
y["foo" as NSString] is Int // true
z["foo"] // Bridging here is automatic though because NSDictionary is untyped leaving compiler freedom to adapt your values
z["foo"] is Int // true
// y.value // error, not defined
// Easiest of all:
let ynot = ["foo": 3]
ynot["foo"] // Introductory swift, no casting needed
ynot["foo"] is Int // Error, type is known at compile time
참고:
'as'
로 String
돌아가 려면를 명시 적으로 사용해야 합니다 NSString
. 브리징은 String
참조 유형 ( NSString
) 보다 값 유형 ( ) 을 사용하기를 원하기 때문에 숨겨지지 않습니다 . 따라서 이것은 의도적으로 더 번거 롭습니다.
참조 유형에 비해 값 유형의 주요 장점 중 하나는 코드에 대해 더 쉽게 추론 할 수 있다는 것입니다. 값 유형에 대한 자세한 내용은 Swift 프로그래밍 언어 (Swift 3)의 클래스 및 구조 및 WWDC 2015 세션 414 Swift에서 값 유형으로 더 나은 앱 빌드를 참조하세요.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다