swift 3.0 Any AnyObject AnyClass

1.AnyObject

AnyObject是一个协议, 它的注释第一行有这么一句话:

The protocol to which all classes implicitly conform.

意思是所有的类都隐式遵守了这个协议.可以表示任何类的实例,任意类的元类型,

  • AnyObject的自动类型转换
    Objective-CNSArray里面只能保存对象类型, 不能添加基本数据类型, 枚举,结构体等.
    Swfit里面将Array的元素类型声明成AnyObject,例如:
        /// 测试字符串
        let str = "123"
        
        /// 测试整型
        let inti = 123
        
        /// 测试Block类型
        let block = {
            print("Hello World")
        }
        /// 测试元组
        let http404Error = (404, "Not Found")
        
        let array: [AnyObject] = [str as AnyObject,inti as AnyObject,http404Error as AnyObject,block as AnyObject]
        
        let strItem = array[0]
        let strM = Mirror(reflecting: strItem)
        print("字符串:\(strM.subjectType)")
        
        let intObj = array[1]
        let intObjM = Mirror(reflecting: intObj)
        print("整型:\(intObjM.subjectType)")
        
        let tupleItem = array[2]
        let tupleM = Mirror(reflecting: tupleItem)
        print("元组:\(tupleM.subjectType)")
        
        let blockItem = array[3]
        let blockM = Mirror(reflecting: blockItem)
        print("闭包:\(blockM.subjectType)")

结果:

字符串:_NSContiguousString
整型:_SwiftTypePreservingNSNumber
元组:_SwiftValue
闭包:_SwiftValue

swift会自动将基本数据类型123转换为NSNumber对象类型

2.Any

可以表示任何类型,包括函数类型、基本数据类型、闭包、元组、枚举、结构体、类

        /// 测试字符串
        let str = "123"
        
        /// 测试整型
        let inti = 123
        
        /// 测试Block类型
        let block = {
            print("Hello World")
        }
        /// 测试元组
        let http404Error = (404, "Not Found")
        
        let array:[Any] = [str ,inti ,http404Error ,block ]
        
        let strItem = array[0]
        let strM = Mirror(reflecting: strItem)
        print("字符串:\(strM.subjectType)")
        
        let intObj = array[1]
        let intObjM = Mirror(reflecting: intObj)
        print("整型:\(intObjM.subjectType)")
        
        let tupleItem = array[2]
        let tupleM = Mirror(reflecting: tupleItem)
        print("元组:\(tupleM.subjectType)")
        
        let blockItem = array[3]
        let blockM = Mirror(reflecting: blockItem)
        print("闭包:\(blockM.subjectType)")

结果:

字符串:String
整型:Int
元组:(Int, String)
闭包:(()) -> ()

数组Array里的元素对应Swift的原生类型

3.AnyClass

public typealias AnyClass = AnyObject.Type

AnyClass: 表示任意类的元类型.任意类的类型都隐式遵守这个协议.

你可能感兴趣的:(swift 3.0 Any AnyObject AnyClass)