问题描述
我阅读了Swift的内联文档,我有点困惑。
I read inline documentation of Swift and I am bit confused.
1)任何
都是一种所有类型都隐式符合的协议。
1) Any
is a protocol that all types implicitly conform.
2) AnyObject
是一个所有类都隐式符合的协议。
2) AnyObject
is a protocol to which all classes implicitly conform.
3) Int
, Float
, Double
是结构
以下是示例代码:
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")
}
我不明白的是为什么 Int
, Double
, Float
是 AnyObject
S'为什么编译器什么都没说?这些类型被声明为结构。 struct MyStruct
无法传递到顶部的方法,因为它不符合 AnyObject
。
What I don't understand is why Int
, Double
, Float
are AnyObject
s? 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
.
你能帮我理解为什么 Int
, Double
和 Float
是 AnyObject
或编译器认为它们为什么?
Could you help me understand why Int
, Double
and Float
are AnyObject
or why compiler thinks they are?
推荐答案
因为您已导入Foundation, Int
, Double
和当传递给一个带有
转换为 AnyObject
的函数时,Float NSNumber
。键入字符串
转换为 NSString
。这样做是为了在调用 Cocoa 和 Cocoa Touch 的界面时简化生活。如果您删除导入UIKit
(或OS $ X的导入Cocoa
),您将看到:
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'
当你打电话时
passAnyObject(a)
描述了值类型到对象的隐式转换
This implicit conversion of value types to objects is described here.
传递 Int
, Double
, String
,或 Bool
到 AnyObject 现在导致错误,例如类型'Int'的参数不符合预期类型'AnyObject'。
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'.
使用Swift 3,已删除隐式类型转换。现在需要投射 Int
, Double
, String
和 Bool
,其中为AnyObject
,以便将其传递给类型 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)
这篇关于是Float,Double,Int是AnyObject吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!