Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 661
Bas Avatar asked Dec 25 '22 11:12

Bas


2 Answers

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

extension Bool : _ObjectiveCBridgeable {
    public init(_ number: NSNumber)
}
like image 75
Rob Napier Avatar answered Mar 16 '23 00:03

Rob Napier


UIKit imports Foundation and Darwin, while Darwin only imports its submodules (like MacTypes).

The Bool Objective-C bridge is only declared in Foundation

extension Bool : _ObjectiveCBridgeable {
    public init(_ number: NSNumber)
}
like image 37
JAL Avatar answered Mar 16 '23 00:03

JAL