Swift casting to a type with a given string, if so ... how? SomeString

I am trying to save a dictionary var items : [String:(type:String,item:AnyObject)] = [:]

for example the "foo" key and items["foo"]?.type = "UILabel"

I want to convert to a AnyObject

given type from a string.

Can you do something like this ?:

                                                 //This is a string
if let myConvertedItem = items["file"]!.item as? items["file"]!.type{
     //myConvertedItem is UILabel here..
}

      

Is there a better way to do this?

edit: I saw this function _stdlib_getTypeName()

but didn't quickly recognize it. how can i declare this? will it work for AnyObject

?

Solution I am not looking for:

do something like this:

if items["file"]!.item is UILabel{
     //ok it UILabel
}

if items["file"]!.item is SomeOtherClassName{
    //ok it some other class name
}

      

because this list can be very long

thank!

+3


source to share


2 answers


Can you do something like this ?:

                                             //This is a string
if let myConvertedItem = items["file"]!.item as? items["file"]!.type{
     //myConvertedItem is UILabel here..
}

      

Not. It's impossible. Swift knows at compile time the types of all of its variables. You can optionclick on a variable and Swift will tell you what it is. You cannot have a variable that assumes a type at runtime.

Take a look at this little example:

let random = arc4random_uniform(2)
let myItem = (random == 0) ? 3 : "hello"

      

You want to myItem

was Int

if random == 0

and String

the if random == 1

, but the compiler does Swift myItem

equal NSObject

, because it handles 3

like NSNumber

and "hello"

how NSString

, so that it can determine the type myItem

.




Even if it worked, what would you do with it? At a point, //myConvertedItem is UILabel here..

Swift would know what myConvertedItem

is UILabel

, but the code you write will not know. You had to do something to know what it was UILabel

before you could do UILabel

things to it.

if items["file"]!.type == "UILabel" {
    // ah, now I know myConvertedItem is a UILabel
    myConvertedItem.text = "hello, world!"
}

      

This will be the same code as you don't want:

if myItem = items["file"]?.item as? UILabel {
    // I know myItem is a UILabel
    myItem.text = "hello, world!"
} 

      

+2


source


Is expression the switch

right solution for you?



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
  }
}

      

+1


source







All Articles