Why do integers not conform to the AnyObject protocol?

前端 未结 3 1335
一个人的身影
一个人的身影 2020-12-18 20:22

Why can I have an [AnyObject] array and put a bunch of different sized types in it ...

var a = [AnyObject]()
a.append(Int(1))
a.append(Float64(3         


        
3条回答
  •  醉梦人生
    2020-12-18 20:48

    There are two kinds of anything types in Swift – Any, which can truly hold anything – a struct, enum or class, and AnyObject, which can only hold classes.

    The reason why it seems like AnyObject can hold structs sometimes is that some specific types are implicitly converted to their NSEquivalent for you as needed, to make Objective-C interop less painful.

    When you write let ao: AnyObject = Int(1), it isn’t really putting an Int into an AnyObject. Instead, it’s implicitly converting your Int into an NSNumber, which is a class, and then putting that in.

    But only some types have this implicit conversion. Int does, but Int32 doesn’t, hence this behaviour:

    // fine
    let aoInt: AnyObject = Int(1) as NSNumber
    // also fine: implicit conversion
    let aoImplicitInt: AnyObject = Int(1)
    // not fine: error: 'Int32' is not convertible to 'NSNumber'
    let aoInt32: AnyObject = Int32(1) as NSNumber
    // but the implicit error is less, ahem, explicit
    // error: type 'Int32' does not conform to protocol 'AnyObject'
    let aoImplicitInt32: AnyObject = Int32(1)
    

    It could be argued there should be more implicit conversions to grease the wheels, but then again, these implicit conversions are the source of much confusion already and the direction in the latest beta is to have fewer of them rather than more.

提交回复
热议问题