我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
只是为了完整起见,基于公认的答案和其他一些答案:
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")
}
}
其他回答
为什么不用这样的东西呢
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中。
斯威夫特3:
class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}
if aShape.isKind(of: Circle.self) {
}
如果你有这样的响应:
{
"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")
}
}
swift4:
if obj is MyClass{
// then object type is MyClass Type
}
是吗?不会总是给出预期的结果,因为as并不测试数据类型是否为特定类型,而只测试数据类型是否可以转换为或表示为特定类型。
以下面的代码为例:
func handleError ( error: Error ) {
if let nsError = error as? NSError {
每个符合Error协议的数据类型都可以转换为NSError对象,所以这总是会成功。但这并不意味着error实际上是一个NSError对象或它的子类。
正确的类型检查应该是:
func handleError ( error: Error ) {
if type(of: error) == NSError.self {
但是,这只检查确切的类型。如果你还想包含NSError的子类,你应该使用:
func handleError ( error: Error ) {
if error is NSError.Type {