AnyObject v.s. Any in Swift

AnyObject

AnyObject can represent an instance of any class type.

1)
AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol.
Example:

class TestB {}
var tmp1: AnyObject = TestB()
var tmp2: AnyObject = TestB.self

2)
AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C counterparts, like String and Int.
Example:

var tmp: AnyObject = "This is a string" as NSString

Any

Any can represent an instance of any type at all, including function types, optional types.
Example:

var closure: () -> Void = {}
var tmp: Any = closure()

Ref:

https://medium.com/@mimicatcodes/any-vs-anyobject-in-swift-3-b1a8d3a02e00
https://developer.apple.com/documentation/swift/anyobject
https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html

探索更多來自 LifeJourney 的內容

立即訂閱即可持續閱讀,還能取得所有封存文章。

Continue reading