Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift,如果让,则由给定字符串强制转换为type。。作为?一些字符串_Ios_Swift_Dynamic_Casting - Fatal编程技术网

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
if
random==0
String
if
random==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
对象,而不是简单的字符串?