Ios Swift,如果让,则由给定字符串强制转换为type。。作为?一些字符串
我正在尝试存储字典Ios Swift,如果让,则由给定字符串强制转换为type。。作为?一些字符串,ios,swift,dynamic,casting,Ios,Swift,Dynamic,Casting,我正在尝试存储字典var items:[String:(type:String,item:AnyObject)]=[:] 例如,键是“foo”和项[“foo”]?。type=“UILabel” 我想从字符串中按给定类型转换为AnyObject 有可能这样做吗 //This is a string if let myConvertedItem = items["file"]!.item as? ite
var items:[String:(type:String,item:AnyObject)]=[:]
例如,键是“foo”和项[“foo”]?。type=“UILabel”
我想从字符串中按给定类型转换为AnyObject
有可能这样做吗
//This is a string
if let myConvertedItem = items["file"]!.item as? items["file"]!.type{
//myConvertedItem is UILabel here..
}
有更好的方法吗
编辑:我看到了这个函数\u stdlib\u getTypeName()
,但swift没有识别它。我怎样才能申报呢?它是否也适用于任何对象
我没有寻找的解决方案:
这样做:
if items["file"]!.item is UILabel{
//ok it's UILabel
}
if items["file"]!.item is SomeOtherClassName{
//ok it's some other class name
}
因为这个if列表可能很长
谢谢 开关表达式是否适合您
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
}
}
有可能这样做吗
//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
ifrandom==0
和String
ifrandom==1
,但是Swift编译器将myItem
变成NSObject
,因为它将3
视为NSNumber
和“hello”
作为NSString
,以便确定myItem
的类型
即使成功了,你会怎么做?在这里,
//myConvertedItem是UILabel..
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,但这仍然是一个问题,这个列表可能很长,我想做一个通用的,我可以保存X类,我怀疑这是不可能的。要在Swift中向对象发送消息,您必须将
AnyObject
转换为特定类型。您是否正在寻找一种动态解决方案,如:?是否尝试在字典中保存AnyClass
对象,而不是简单的字符串?