美文网首页
利用协议实现类型判断

利用协议实现类型判断

作者: 得_道 | 来源:发表于2020-11-08 20:07 被阅读0次

首先看一个例子
判断是不是数组

func isArray(_ value: Any) -> Bool {
    value is [Any]
}

isArray([1, 2])
isArray(["1", 2])
isArray(NSArray())
isArray(NSMutableArray())
isArray("123")

打印的结果如下:

true
true
true
true
false

如果要判断是不是数组是不是数组类型呢?
假如还仿照上面的写法

func isArrayType(_ value: Any.Type) -> Bool {
    value is [Any].Type
}

print(isArrayType([Int].self))
print(isArrayType([Any].self))
print(isArrayType(NSArray.self))
print(isArrayType(NSMutableArray.self))
print(isArrayType(String.self))

打印结果

false
true
false
false
false

可以发现只有第二个位true,其余都是false
为什么跟判断实例结果不一样呢?
原因是[Int].Typetype[Any].Typetype不是同一个type
怎么做呢?
这里就可以利用协议,代码如下

protocol ArrayType{}
extension Array: ArrayType {}
extension NSArray: ArrayType {}

func isArrayType(_ value: Any.Type) -> Bool {
    value is ArrayType.Type
}

print(isArrayType([Int].self))
print(isArrayType([Any].self))
print(isArrayType(NSArray.self))
print(isArrayType(NSMutableArray.self))
print(isArrayType(String.self))

打印结果

true
true
true
true
false

可以发现前面四个都是true
这就是利用协议来实现类型判断

相关文章

网友评论

      本文标题:利用协议实现类型判断

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