我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
我有两种方法:
if let thisShape = aShape as? Square
Or:
aShape.isKindOfClass(Square)
下面是一个详细的例子:
class Shape { }
class Square: Shape { }
class Circle: Shape { }
var aShape = Shape()
aShape = Square()
if let thisShape = aShape as? Square {
println("Its a square")
} else {
println("Its not a square")
}
if aShape.isKindOfClass(Square) {
println("Its a square")
} else {
println("Its not a square")
}
编辑:3现在:
let myShape = Shape()
if myShape is Shape {
print("yes it is")
}
其他回答
为什么不使用专门为此任务构建的内置功能呢?
let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)
Result: "Array<Any>"
swift4:
if obj is MyClass{
// then object type is MyClass Type
}
myObject一样吗?如果myObject不是String, String返回nil。否则,它返回一个字符串?,所以你可以使用myObject访问字符串本身!,或者使用myObject强制转换它!作为字符串安全。
let originalArray : [Any?] = ["Hello", "World", 111, 2, nil, 3.34]
let strings = originalArray.compactMap({ $0 as? String })
print(strings)
//printed: ["Hello", "World"]
假设drawTriangle是UIView的一个实例。检查drawTriangle是否为UITableView类型:
在Swift 3中,
if drawTriangle is UITableView{
// in deed drawTriangle is UIView
// do something here...
} else{
// do something here...
}
这也可以用于你自己定义的类。你可以用它来检查视图的子视图。