Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

ios - Is Float, Double, Int an AnyObject?

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

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

2) AnyObject is a protocol to which all classes implicitly conform.

3) Int, Float, Double are structs

Here is a sample code:

import UIKit

func passAnyObject(param: AnyObject) {
    print(param)
}

class MyClass {}
struct MyStruct {}

let a: Int = 1
let b = 2.0
let c = NSObject()
let d = MyClass()
let e = MyStruct()

passAnyObject(a)
passAnyObject(b)
passAnyObject(c)
passAnyObject(d)
//passAnyObject(e) // Argument type 'MyStruct' does not conform to expected type 'AnyObject'


if a is AnyObject { // b, d, e is also AnyObject
    print("(a.dynamicType) is AnyObject")
}

What I don't understand is why Int, Double, Float are AnyObjects? Why compiler doesn't say anything? Those types are declared as structs. Struct MyStruct cannot be passed to the method on the top because it does not conform to AnyObject.

Could you help me understand why Int, Double and Float are AnyObject or why compiler thinks they are?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...