我试图存储字典var items : [String:(type:String,item:AnyObject)] = [:]
items["foo"]?.type = "UILabel"
我想从字符串中按给定类型转换为AnyObject
。
是否可以做这样的事情?:
//This is a string
if let myConvertedItem = items["file"]!.item as? items["file"]!.type{
//myConvertedItem is UILabel here..
}
有更好的方法吗?
编辑:我看到了这个函数_stdlib_getTypeName()
,但是swift并没有认出它。我怎么能宣布它?它会在AnyObject
上发挥作用吗?
解决方案我不是在寻找:
做这样的事情:
if items["file"]!.item is UILabel{
//ok it's UILabel
}
if items["file"]!.item is SomeOtherClassName{
//ok it's some other class name
}
因为这个if列表可能很长 p>
谢谢!
答案 0 :(得分:4)
是否可以做这样的事情?:
//This is a string
if let myConvertedItem = items["file"]!.item as? items["file"]!.type{
//myConvertedItem is UILabel here..
}
没有。这是不可能的。 Swift在编译时知道所有变量的类型。你可以选项 - 点击变量,Swift会告诉你它是什么。在运行时假设类型不能有变量。
看看这个小例子:
let random = arc4random_uniform(2)
let myItem = (random == 0) ? 3 : "hello"
您希望myItem
成为Int
如果random == 0
而String
如果random == 1
,但Swift编译器会myItem
成为NSObject
因为它将3
视为NSNumber
而"hello"
视为NSString
,因此可以确定myItem
的类型}。
即使这样有效,你会用它做什么?在//myConvertedItem is UILabel here..
时,Swift会知道myConvertedItem
是UILabel
,但您编写的代码不会知道。您必须先执行某些才能知道它是UILabel
,然后才能对其进行UILabel
事情。
if items["file"]!.type == "UILabel" {
// ah, now I know myConvertedItem is a UILabel
myConvertedItem.text = "hello, world!"
}
与您不想这样做的代码数量相同:
if myItem = items["file"]?.item as? UILabel {
// I know myItem is a UILabel
myItem.text = "hello, world!"
}
答案 1 :(得分:2)
switch
表达式是否适合您?
if let item: AnyObject = items["file"]?.item {
switch item {
case let label as UILabel:
// do something with UILabel
case let someOtherClass as SomeOtherClassName:
// do something with SomeOtherClass
default:
break
}
}