[英]How to map UIImage, UILabel and UIView contents to a String in Swift?
从API调用接收到String
。 该字符串基本上定义了UIImage
, UILabel
和UIView
的标签。 此API调用可以接收9种类型的字符串。 我有以下代码来映射这些:
struct Map{
var image : UIImage!
var title : String!
func getProperties(stringFromAPI : String) {
switch stringFromAPI {
case "fireFS":
self.image = UIImage(string: "fireFS")
self.title = "Fire"
case "chromeFS":
self.image = UIImage(string: "chrome_FS_1")
self.title = "Chromatic"
default:
break
}
} }
有没有一种有效的方法来在枚举中设置所有这些属性并在全局范围内检索它? 任何帮助将不胜感激和支持。 谢谢。
您可以定义一个全局词典,例如:
struct ExampleDict {
static let data: [String: [String: Any]] = [
"fireFS": [
"imageName": "fireFS",
"title": "Fire"
],
"chromeFS": [
"imageName": "chrome_FS_1",
"title": "Chromatic"
]
]
}
在这里,您将每个元组的键设置为您希望从API获得的字符串,即stringFromAPI
。 然后,您可以在其中添加imageName,title和任何其他元组。
为了从字典中检索值,只需将其像数组一样下标即可:
if let imageName = ExampleDict.data["chromeFS"]?["imageName"] {
print(imageName)
}
现在,让我们将其与您现有的代码集成在一起:
func getProperties(stringFromAPI : String) {
if let imageName = ExampleDict.data[stringFromAPI]?["imageName"] {
print(imageName)
}
if let imageTitle = ExampleDict.data[stringFromAPI]?["title"] {
print(imageTitle)
}
}
让我们尝试一下...
getProperties(stringFromAPI: "fireFS")
/// Output
// fireFS
// Fire
getProperties(stringFromAPI: "chromeFS")
/// Output
// chrome_FS_1
// Chromatic
enum ImageMapping: String {
case fireFS = "fireFS"
case chromeFS = "chromeFS"
func imageName() -> String {
switch self {
case .fireFS:
return "Fire"
case .chromeFS:
return "Chromatic"
}
}
}
func getProperties(stringFromAPI : String) {
let mapping = ImageMapping(rawValue: stringFromAPI)
self.image = UIImage(string: stringFromAPI)
self.title = mapping?.imageName()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.