Is Float, Double, Int an AnyObject?

前端 未结 3 1826
执念已碎
执念已碎 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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)
    

提交回复
热议问题