我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
请注意:
var string = "Hello" as NSString
var obj1:AnyObject = string
var obj2:NSObject = string
print(obj1 is NSString)
print(obj2 is NSString)
print(obj1 is String)
print(obj2 is String)
最后四行都返回true,这是因为如果你输入
var r1:CGRect = CGRect()
print(r1 is String)
... 它打印“假”当然,但警告说,Cast从CGRect到字符串失败。因此有些类型是桥接的,'is'关键字调用隐式强制转换。
你最好使用其中的一个:
myObject.isKind(of: MyClass.self))
myObject.isMember(of: MyClass.self))
其他回答
myObject一样吗?如果myObject不是String, String返回nil。否则,它返回一个字符串?,所以你可以使用myObject访问字符串本身!,或者使用myObject强制转换它!作为字符串安全。
我有两种方法:
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 somvariable…),你可以简单地用一个布尔值替换let:
if (yourObject as? ClassToCompareWith) != nil {
// do what you have to do
}
else {
// do something else
}
Xcode在我使用let方法而没有使用定义值时提出了这个建议。
为什么不用这样的东西呢
fileprivate enum types {
case typeString
case typeInt
case typeDouble
case typeUnknown
}
fileprivate func typeOfAny(variable: Any) -> types {
if variable is String {return types.typeString}
if variable is Int {return types.typeInt}
if variable is Double {return types.typeDouble}
return types.typeUnknown
}
在Swift 3中。
如果您不知道您将从服务器的响应中获得一个字典数组或单个字典,则需要检查结果是否包含数组。 在我的情况下,总是接收一个字典数组,除了一次。所以,为了处理这个问题,我使用了下面的swift 3代码。
if let str = strDict["item"] as? Array<Any>
在这里吗?Array检查获取的值是否为Array(字典项)。在其他情况下,你可以处理,如果它是一个字典项,而不是保存在数组中。