Is Float, Double, Int an AnyObject?

前端 未结 3 1794
执念已碎
执念已碎 2021-01-07 19:49

I read inline documentation of Swift and I am bit confused.

1) Any is a protocol that all types implicitly conform.

2) AnyObject

相关标签:
3条回答
  • 2021-01-07 20:30

    Good find! UIKit actually converts them to NSNumber - also mentioned by @vacawama. The reason for this is, sometimes you're working with code that returns or uses AnyObject, this object could then be cast (as!) as an Int or other "structs".

    0 讨论(0)
  • 2021-01-07 20:37

    Because you have Foundation imported, Int, Double, and Float get converted to NSNumber when passed to a function taking an AnyObject. Type String gets converted to NSString. This is done to make life easier when calling Cocoa and Cocoa Touch based interfaces. If you remove import UIKit (or import Cocoa for OS X), you will see:

    error: argument type 'Int' does not conform to expected type 'AnyObject'
    

    when you call

    passAnyObject(a)
    

    This implicit conversion of value types to objects is described here.


    Update for Swift 3 (Xcode 8 beta 6):

    Passing an Int, Double, String, or Bool to a parameter of type AnyObject now results in an error such as Argument of type 'Int' does not conform to expected type 'AnyObject'.

    With Swift 3, implicit type conversion has been removed. It is now necessary to cast Int, Double, String and Bool with as AnyObject in order to pass it to a parameter of type AnyObject:

    let a = 1
    passAnyObject(a as AnyObject)
    
    0 讨论(0)
  • 2021-01-07 20:43
    class Test {
    
    static func test() {
        let anyObjectsValues: [AnyObject] = [1, "Two", 3, "Four"] as [AnyObject]
        anyObjectsValues.forEach { (value) in
            switch value {
            case is Int:
                print("\(value) is an Int!")
            case is String:
                print("\(value) is a String!")
            default:
                print("\(value) is some other type!")
            }
        }
    }
    

    }

    I have not imported UIKit or Foundation frameworks. Why compiler is not giving any error? Even it printing the result.

    Output:

    1 is an Int!

    Two is a String!

    3 is an Int!

    Four is a String!

    Does anybody have an idea?

    0 讨论(0)
提交回复
热议问题