如何将UIImage,UILabel和UIView内容映射到Swift中的字符串?

问题描述:

从API调用接收到String。这个字符串基本上定义了什么UIImageUILabelUIView的标签。有9种类型的字符串可以通过此API调用接收。我有以下代码映射这些:如何将UIImage,UILabel和UIView内容映射到Swift中的字符串?

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

是否有一个枚举设置所有这些属性和全球检索它的有效方法是什么?任何帮助将不胜感激和upvoted。谢谢。

可以定义一个全局字典,如:

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() 

    } 
+0

using this ans更有可能通过使用它的imageName属性取回枚举的原始值?这个解决方案看起来不错,所以我想澄清一下,如果反向查找是可能的。谢谢。 –

+0

然后你需要编写另一个函数来做到这一点。 – Noot