Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

  • "AnyObject can represent an instance of any class type.

  • Bool is a struct

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!")
}

like image 360
Rembrandt Q. Einstein Avatar asked Jun 08 '16 15:06

Rembrandt Q. Einstein


People also ask

What is the difference between any and AnyObject?

AnyObject is only for reference types (classes), Any is for both value and reference types. So you should go for [String: Any] . Swift provides two special types for working with nonspecific types: Any can represent an instance of any type at all, including function types.

What is AnyObject?

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.

What is true about AnyObject data type in Swift?

Any and AnyObject are two special types in Swift that are used for working with non-specific types. According to Apple's Swift documentation, Any can represent an instance of any type at all, including function types and optional types. AnyObject can represent an instance of any class type.


2 Answers

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))
like image 98
Alexander Avatar answered Sep 18 '22 08:09

Alexander


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.

like image 32
JAL Avatar answered Sep 20 '22 08:09

JAL