Why can I return a bool with the return type of AnyObject? with UIKit, not Darwin

I was typing some Swift code because I was bored and didn't program Swift after a while.

Why does this code work when I turn on 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()

And when I import Darwin instead of UIKit, it does not work.

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

This is the same code, except that I changed UIKit to Darwin. The error says that you cannot return the bool type in AnyObject?

It does not give an error message when I turn on UIKit.

Does anyone know what causes this?

+4
source share
3 answers

FoundationAdds an automatic bridge between Booland NSNumber(which is AnyObject).

extension Bool : _ObjectiveCBridgeable {
    public init(_ number: NSNumber)
}
+5

UIKit Foundation Darwin, Darwin (, MacTypes).

Bool Objective-C Foundation

extension Bool : _ObjectiveCBridgeable {
    public init(_ number: NSNumber)
}
+4
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, "", , , " " . , . , - 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
+1

Source: https://habr.com/ru/post/1618635/


All Articles