我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
我有一个由AnyObject组成的数组。我想遍历它,找到所有数组实例的元素。
我怎么能检查如果一个对象是一个给定的类型在Swift?
当前回答
为什么不用这样的东西呢
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) {
}
在Swift 2.2 - 5你现在可以做:
if object is String
{
}
然后过滤你的数组:
let filteredArray = originalArray.filter({ $0 is Array })
如果你有多个类型需要检查:
switch object
{
case is String:
...
case is OtherClass:
...
default:
...
}
如果你想检查一个特定的类型,你可以做以下事情:
if let stringArray = obj as? [String] {
// obj is a string array. Do something with stringArray
}
else {
// obj is not a string array
}
你可以使用"as!",如果obj不是[String]类型,就会抛出一个运行时错误。
let stringArray = obj as! [String]
你也可以一次检查一个元素:
let items : [Any] = ["Hello", "World"]
for obj in items {
if let str = obj as? String {
// obj is a String. Do something with str
}
else {
// obj is not a String
}
}
如果你只想知道一个对象是否是给定类型的子类型,那么有一个更简单的方法:
class Shape {}
class Circle : Shape {}
class Rectangle : Shape {}
func area (shape: Shape) -> Double {
if shape is Circle { ... }
else if shape is Rectangle { ... }
}
"使用类型检查操作符(is)来检查实例是否属于某个类型 子类的类型。如果实例为,则类型检查操作符返回true 如果不是,则为false "摘自:苹果公司《快速编程语言》。“iBooks。
在上面的句子中,“of a certain subclass type”很重要。is Circle和is Rectangle的使用被编译器接受,因为该值shape被声明为shape (Circle和Rectangle的超类)。
如果您使用的是基本类型,超类将是Any。这里有一个例子:
21> func test (obj:Any) -> String {
22. if obj is Int { return "Int" }
23. else if obj is String { return "String" }
24. else { return "Any" }
25. }
...
30> test (1)
$R16: String = "Int"
31> test ("abc")
$R17: String = "String"
32> test (nil)
$R18: String = "Any"
为什么不使用专门为此任务构建的内置功能呢?
let myArray: [Any] = ["easy", "as", "that"]
let type = type(of: myArray)
Result: "Array<Any>"