Swift,如果允许的话,按给定的字符串强制转换为? someString

时间:2015-08-02 08:28:59

标签: ios swift dynamic casting

我试图存储字典var items : [String:(type:String,item:AnyObject)] = [:]

例如,密钥是" foo"和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列表可能很长

谢谢!

2 个答案:

答案 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 == 0String如果random == 1,但Swift编译器会myItem成为NSObject因为它将3视为NSNumber"hello"视为NSString,因此可以确定myItem的类型}。

即使这样有效,你会用它做什么?在//myConvertedItem is UILabel here..时,Swift会知道myConvertedItemUILabel,但您编写的代码不会知道。您必须先执行某些才能知道它是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
  }
}