Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - Why do integers not conform to the AnyObject protocol?

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.14))
a.append(Bool(true))

... except for Int32 and Int64 ....

a.append(Int32(1)) // err: type 'Int32' does not conform to protocol 'AnyObject'
a.append(Int64(1)) // err: type 'Int64' does not conform to protocol 'AnyObject'

The documentation for AnyObject says:

“AnyObject can represent an instance of any class type”

But when I command-click on Int, Int32 or Int64 to see the standard library definition of these types, I see that they are all struct values.

What is the underlying issue here? Why is this designed like this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...