[英]Why can I return a bool with return type AnyObject? with UIKit and not with Darwin
我正在鍵入一些Swift代碼,因為我很無聊並且一段時間沒有編寫Swift。
當我包含UIKit時,為什么這段代碼有用呢?
import UIKit
public class foo {
private var boolTest : Bool?
init() {
boolTest = true
}
public func call() -> AnyObject? {
if let bool = boolTest {
return bool
}
else {
return nil
}
}
}
foo().call()
當我導入Darwin而不是UIKit時,它不起作用。
import Darwin
public class foo {
private var boolTest : Bool?
init() {
boolTest = true
}
public func call() -> AnyObject? {
if let bool = boolTest {
return bool
}
else {
return nil
}
}
}
foo().call()
除了我將UIKit改為達爾文之外,它的代碼完全相同。 錯誤說不能將類型bool返回給AnyObject?
當我包含UIKit時,它不會給出錯誤消息。
那么有誰知道是什么原因造成的?
Foundation
將Bool
自動橋接添加到NSNumber
(這是一個AnyObject
)。
extension Bool : _ObjectiveCBridgeable {
public init(_ number: NSNumber)
}
UIKit
導入Foundation
和Darwin
,而Darwin
只導入其子模塊(如MacTypes
)。
Bool
Objective-C橋只在Foundation
宣布
extension Bool : _ObjectiveCBridgeable {
public init(_ number: NSNumber)
}
import Foundation
let a: AnyObject = true
print(a, a.dynamicType) // 1 __NSCFBoolean
let b: Bool = true
print(b, b.dynamicType) // true Bool
在某些原生swift和Objective C之間存在“自由橋接”。我個人討厭這種“自動”橋接,相反,如果你需要將swift與Objective C混合,它可以幫助你編寫“更干凈”的代碼。 有很多可用的代碼,其中“免費橋接”是不需要的功能的來源。 我建議你盡可能多地使用原生的swift類型。 我真的不明白為什么有人需要為AnyObject類型的變量賦值布爾值的想法....
檢查這個'智能'結構
a as! NSObject == 1 // true
//a == true // error !!!!!!
a as! NSObject == true // true
//a == b as AnyObject // error !!
//a as Bool == b // error
a as! Bool == b // true
a as! UInt == 1 // true
a as! Double == 1 // true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.