我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
如果你有这样的响应:
{
"registeration_method": "email",
"is_stucked": true,
"individual": {
"id": 24099,
"first_name": "ahmad",
"last_name": "zozoz",
"email": null,
"mobile_number": null,
"confirmed": false,
"avatar": "http://abc-abc-xyz.amazonaws.com/images/placeholder-profile.png",
"doctor_request_status": 0
},
"max_number_of_confirmation_trials": 4,
"max_number_of_invalid_confirmation_trials": 12
}
你想检查值is_stuck将被读取为AnyObject,你所要做的就是这个
if let isStucked = response["is_stucked"] as? Bool{
if isStucked{
print("is Stucked")
}
else{
print("Not Stucked")
}
}
其他回答
只是为了完整起见,基于公认的答案和其他一些答案:
let items : [Any] = ["Hello", "World", 1]
for obj in items where obj is String {
// obj is a String. Do something with str
}
但是你也可以(compactMap也“映射”过滤器没有的值):
items.compactMap { $0 as? String }.forEach{ /* do something with $0 */ ) }
以及一个使用switch的版本:
for obj in items {
switch (obj) {
case is Int:
// it's an integer
case let stringObj as String:
// you can do something with stringObj which is a String
default:
print("\(type(of: obj))") // get the type
}
}
但回到问题上来,检查它是否是一个数组(即[String]):
let items : [Any] = ["Hello", "World", 1, ["Hello", "World", "of", "Arrays"]]
for obj in items {
if let stringArray = obj as? [String] {
print("\(stringArray)")
}
}
或者更一般地说(见另一个问题的答案):
for obj in items {
if obj is [Any] {
print("is [Any]")
}
if obj is [AnyObject] {
print("is [AnyObject]")
}
if obj is NSArray {
print("is NSArray")
}
}
我有两种方法:
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")
}
myObject一样吗?如果myObject不是String, String返回nil。否则,它返回一个字符串?,所以你可以使用myObject访问字符串本身!,或者使用myObject强制转换它!作为字符串安全。
你可以使用这个函数,然后调用它:
func printInfo(_ value: Any) {
let t = type(of: value)
print("'\(value)' of type '\(t)'")
}
例如:printInfo(data)
数据类型为“125字节”
在Swift 2.2 - 5你现在可以做:
if object is String
{
}
然后过滤你的数组:
let filteredArray = originalArray.filter({ $0 is Array })
如果你有多个类型需要检查:
switch object
{
case is String:
...
case is OtherClass:
...
default:
...
}