首先看一个例子
判断是不是数组
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].Type
的type
与[Any].Type
的type
不是同一个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
这就是利用协议来实现类型判断
网友评论