我有一个由AnyObject
组成的数组。我想遍历它,并找到所有是数组实例的元素。
如何在Swift中检查对象是否为特定类型?
我有一个由AnyObject
组成的数组。我想遍历它,并找到所有是数组实例的元素。
如何在Swift中检查对象是否为特定类型?
func printInfo(_ value: Any) {
let t = type(of: value)
print("'\(value)' of type '\(t)'")
}
printInfo(data)
'125 字节' 的类型为 'Data'
Swift 4.2,在我的情况下,使用isKind函数。
isKind(of :)返回一个布尔值,指示接收器是否是给定类的实例或继承自该类的任何类的实例。
注意:翻译中的代码保留了英文原文。
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
myObject as? String
如果 myObject
不是 String
类型,返回 nil
。否则,它会返回一个 String?
,因此您可以使用 myObject!
访问字符串本身,或者使用 myObject! as String
进行安全转换。
为什么不使用像这样的东西
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中。
如果你只是想检查类而不因未使用定义值(让一些变量…)而收到警告,你可以简单地用布尔值替换let语句:
if (yourObject as? ClassToCompareWith) != nil {
// do what you have to do
}
else {
// do something else
}
Swift 3:
class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}
if aShape.isKind(of: Circle.self) {
}
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.")
}
if let str = strDict["item"] as? Array<Any>
在这里,我们检查获取的值是否为数组(字典项的数组)。否则情况下,你可以处理它是否是单个字典项,而不是保存在数组中。
{
"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_stucked
,它将被读取为 AnyObject,你只需要这样做
if let isStucked = response["is_stucked"] as? Bool{
if isStucked{
print("is Stucked")
}
else{
print("Not Stucked")
}
}
let originalArray : [Any?] = ["Hello", "World", 111, 2, nil, 3.34]
let strings = originalArray.compactMap({ $0 as? String })
print(strings)
//printed: ["Hello", "World"]