微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试存储字典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列表可能很长

谢谢!

解决方法

is it possible to do something like this?:

//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,如果随机== 0,一个字符串,如果随机== 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!"
}

原文地址:https://www.jb51.cc/iOS/328480.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐