我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
Swift 5.2 & Xcode版本:11.3.1(11C504)
以下是我检查数据类型的解决方案:
if let typeCheck = myResult as? [String : Any] {
print("It's Dictionary.")
} else {
print("It's not Dictionary.")
}
我希望它能帮助你。
其他回答
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
swift4:
if obj is MyClass{
// then object type is MyClass Type
}
假设drawTriangle是UIView的一个实例。检查drawTriangle是否为UITableView类型:
在Swift 3中,
if drawTriangle is UITableView{
// in deed drawTriangle is UIView
// do something here...
} else{
// do something here...
}
这也可以用于你自己定义的类。你可以用它来检查视图的子视图。
你可以使用这个函数,然后调用它:
func printInfo(_ value: Any) {
let t = type(of: value)
print("'\(value)' of type '\(t)'")
}
例如:printInfo(data)
数据类型为“125字节”
如果你有这样的响应:
{
"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")
}
}