【问题标题】:How to map UIImage, UILabel and UIView contents to a String in Swift?如何将 UIImage、UILabel 和 UIView 内容映射到 Swift 中的字符串?
【发布时间】:2017-10-12 01:03:26
【问题描述】:

从 API 调用接收到 String。这个字符串基本上定义了UIImageUILabelUIView的标签。可以从此 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
    }
} }

是否有一种有效的方法可以在枚举中设置所有这些属性并在全局范围内检索它?任何帮助将不胜感激和赞成。谢谢。

【问题讨论】:

    标签: ios swift struct tags


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:
          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()
      
          }
      

      【讨论】:

      • 使用这个答案是否可以通过使用它的 imageName 属性来取回枚举的原始值?这个解决方案看起来很棒,所以我想澄清一下是否可以进行反向查找。谢谢。
      • 那你需要写另外一个函数来做。
      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2012-01-23
      相关资源
      最近更新 更多