Search code examples
iosswiftuikitdarwin

Why can I return a bool with return type AnyObject? with UIKit and not with Darwin


I was typing some Swift code, because I was bored and haven't programmed Swift in a while.

Why does this code work when I include 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 doesn't 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()

Its the exact same code except I changed UIKit to Darwin. The error says can't return type bool to AnyObject?

It doesn't give the error message when I include UIKit.

So does anyone know what causes this?


Solution

  • Foundation adds automatic bridging from Bool to NSNumber (which is an AnyObject).

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