我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
let originalArray : [Any?] = ["Hello", "World", 111, 2, nil, 3.34]
let strings = originalArray.compactMap({ $0 as? String })
print(strings)
//printed: ["Hello", "World"]
其他回答
如果你想检查一个特定的类型,你可以做以下事情:
if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}
你可以使用"as!",如果obj不是[String]类型,就会抛出一个运行时错误。
let stringArray = obj as! [String]
你也可以一次检查一个元素:
let items : [Any] = ["Hello", "World"]
for obj in items {
if let str = obj as? String {
// obj is a String. Do something with str
}
else {
// obj is not a String
}
}
Swift 4.2,在我的情况下,使用isKind函数。
isKind (:) 返回一个布尔值,该值指示接收者是给定类的实例还是从该类继承的任何类的实例。
let items : [AnyObject] = ["A", "B" , ... ]
for obj in items {
if(obj.isKind(of: NSString.self)){
print("String")
}
}
阅读更多 https://developer.apple.com/documentation/objectivec/nsobjectprotocol/1418511-iskind
如果您不知道您将从服务器的响应中获得一个字典数组或单个字典,则需要检查结果是否包含数组。 在我的情况下,总是接收一个字典数组,除了一次。所以,为了处理这个问题,我使用了下面的swift 3代码。
if let str = strDict["item"] as? Array<Any>
在这里吗?Array检查获取的值是否为Array(字典项)。在其他情况下,你可以处理,如果它是一个字典项,而不是保存在数组中。
我有两种方法:
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")
}
斯威夫特3:
class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}
if aShape.isKind(of: Circle.self) {
}