美文网首页
Swift3.x - Any、AnyObject和AnyClas

Swift3.x - Any、AnyObject和AnyClas

作者: ibabyblue | 来源:发表于2017-04-21 15:45 被阅读95次

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


    Any、AnyObject

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

    • Any can represent an instance of any type at all, including function types.
    • AnyObject can represent an instance of any class type.

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

    • AnyObject
      AnyObject在API中的声明:
    @objc public protocol AnyObject {
    }
    

    并且在官方注释为:

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

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

    • Any
      Any:天下我最大,可以代表任意类型的实例。
      官方文档给出了一个例子:
        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!

    • AnyClass
      AnyClass在API中的声明:
    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

    相关文章

      网友评论

          本文标题:Swift3.x - Any、AnyObject和AnyClas

          本文链接:https://www.haomeiwen.com/subject/mbfdzttx.html