Swift3.x - Any、AnyObject和AnyClas

2017-04-21  本文已影响95人  ibabyblue

在Swift中使用AnyObject遇到的问题:方法回调的参数类型不确定,设置接收AnyObject,传参数的时候,传入String类型,会导致编译报错!


Any、AnyObject

Swift为不确定类型提供了两种特殊类型:

Any:代表任意类型实例,包括方法类型。
AnyObject:代表任意'类(class)'类型的实例。

@objc public protocol AnyObject {
}

并且在官方注释为:

/// The protocol to which all classes implicitly conform.

可见AnyObject为一个空协议,并且默认所有Class均隐式遵循此协议!

    var things = [Any]()
    things.append(0)
    things.append(0.0)
    things.append(42)
    things.append(3.14159)
    things.append("hello")
    things.append((3.0, 5.0))
    things.append({ (name: String) -> String in "Hello, \(name)" })

Any类型的数组中包含了各种类型的数据,包括非Class类型的String类型,在Swfit中的String为结构体类型。
Any是可以代表函数类型的,举个栗子:

  class ViewController: UIViewController {

      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

          sayWhat(str: sayHello())
        
      }
      func sayWhat(str : Any){
        
        print("i say \(str)")
    
      }
    
      func sayHello() -> String{
          return "hello world!"
      }
    
  }

结果输出:i say hello world!

public typealias AnyClass = AnyObject.Type

并且官方文档的注释为:

/// The protocol to which all classes implicitly conform.

AnyClass仅为AnyObject.Type的别名!通过 AnyObject.Type 这种方式所得到是一个元类型 (Meta)。
详情参阅喵神的文章:
传送门:http://swifter.tips/self-anyclass/
Zeb

上一篇下一篇

猜你喜欢

热点阅读