Rembrandt Q. Einstein
Rembrandt Q. Einstein

Reputation: 1121

Why is Bool "AnyObject" instead of "Any"?

I have a simple question: Why does Bool qualify as AnyObject According to Apple's documentation:

So why does this statement pass?

let bool = true
let explicitBool: Bool = true

if (bool is AnyObject){
    print("I'm an object")
}

if (explicitBool is AnyObject){
    print("I'm still an object!")
}

Upvotes: 9

Views: 1561

Answers (2)

JAL
JAL

Reputation: 42449

This behavior is due to the Playground runtime bridging to Objective-C/Cocoa APIs behind-the-scenes. Swift version 3.0-dev (LLVM 8fcf602916, Clang cf0a734990, Swift 000d413a62) on Linux does not reproduce this behavior, with or without Foundation imported

let someBool = true
let someExplicitBool: Bool = true

print(someBool.dynamicType) // Bool
print(someExplicitBool.dynamicType) // Bool

print(someBool is AnyObject) // false
print(someExplicitBool is AnyObject) // fase

Try it online.

Upvotes: 4

Alexander
Alexander

Reputation: 63167

Because it's being bridged to an NSNumber instance.

Swift automatically bridges certain native number types, such as Int and Float, to NSNumber. - Using Swift with Cocoa and Objective-C (Swift 2.2) - Numbers

Try this:

let test = bool as AnyObject
print(String(test.dynamicType))

Upvotes: 8

Related Questions