【问题标题】:How do I remove optional text from UILabel如何从 UILabel 中删除可选文本
【发布时间】:2018-12-25 21:15:33
【问题描述】:

当我运行应用程序时,我正在尝试删除 UILabel 上的 Optional 文本。但是,我已经尝试了很多方法,Optional 仍然存在。

重要的是,我从JSON 获得了这些值,因此我创建了一个Struct 来解码所有这些数据。属性ibu 是唯一一个写有Optional 的属性,但如果我删除? 我在JSONDecoder 上收到错误消息:

Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 23", intValue: 23), CodingKeys(stringValue: "ibu", intValue: nil)], debugDescription: "预期为 Double 值,但发现为 null。", 底层错误:无))

我该如何解决这个问题?

应用图片:

模型文件夹:

  struct Cerveja:Decodable{
        let name:String
        let image_url:String
        let description:String
        let tagline:String
        let abv:Double
        let ibu:Double? //This one that I got the "Optional" written in the UILabel
                        //If I remove the "?" I got the error below
    }

查看文件夹 - 详细信息屏幕:

var item:Cerveja?

override func viewDidLoad() {
    super.viewDidLoad()

    labelName.text = item?.name
    labelDescricao.text = item?.description
    labelAmargor.text = "\(String(describing: item!.ibu))" 
    labelTeorAlc.text = "\(item!.abv)"

    let resource = ImageResource(downloadURL: URL(string: "\(item?.image_url ?? "")")!, cacheKey: item?.image_url)
    imageDetail.kf.setImage(with: resource)
}

网络文件夹:

func getApiData(completion: @escaping ([Cerveja]) -> ()){
    guard let urlString = URL(string: "https://api.punkapi.com/v2/beers") else {
        print("URL Error")
        return
    }
    Alamofire.request(urlString).responseJSON { response in

        if response.data == response.data{
            do{
                let decoder = try JSONDecoder().decode([Cerveja].self, from: response.data!)

                completion(decoder)
            }catch{
        print(error)
            }
        }else{print("API Response is Empty")}

        }
}

JSON:

[
  {
    "id": 1,
    "name": "Buzz",
    "tagline": "A Real Bitter Experience.",
    "first_brewed": "09\/2007",
    "description": "A light, crisp and bitter IPA brewed with English and American hops. A small batch brewed only once.",
    "image_url": "https:\/\/images.punkapi.com\/v2\/keg.png",
    "abv": 4.5,
    "ibu": 60,
    "target_fg": 1010,
    "target_og": 1044,
    "ebc": 20,
    "srm": 10,
    "ph": 4.4,
    "attenuation_level": 75,
    "volume": {
      "value": 20,
      "unit": "liters"
    },
    "boil_volume": {
      "value": 25,
      "unit": "liters"
    },
    "method": {
      "mash_temp": [
        {
          "temp": {
            "value": 64,
            "unit": "celsius"
          },
          "duration": 75
        }
      ],
      "fermentation": {
        "temp": {
          "value": 19,
          "unit": "celsius"
        }
      },
      "twist": null
    },
    "ingredients": {
      "malt": [
        {
          "name": "Maris Otter Extra Pale",
          "amount": {
            "value": 3.3,
            "unit": "kilograms"
          }
        },
        {
          "name": "Caramalt",
          "amount": {
            "value": 0.2,
            "unit": "kilograms"
          }
        },
        {
          "name": "Munich",
          "amount": {
            "value": 0.4,
            "unit": "kilograms"
          }
        }
      ],
      "hops": [
        {
          "name": "Fuggles",
          "amount": {
            "value": 25,
            "unit": "grams"
          },
          "add": "start",
          "attribute": "bitter"
        },
        {
          "name": "First Gold",
          "amount": {
            "value": 25,
            "unit": "grams"
          },
          "add": "start",
          "attribute": "bitter"
        },
        {
          "name": "Fuggles",
          "amount": {
            "value": 37.5,
            "unit": "grams"
          },
          "add": "middle",
          "attribute": "flavour"
        },
        {
          "name": "First Gold",
          "amount": {
            "value": 37.5,
            "unit": "grams"
          },
          "add": "middle",
          "attribute": "flavour"
        },
        {
          "name": "Cascade",
          "amount": {
            "value": 37.5,
            "unit": "grams"
          },
          "add": "end",
          "attribute": "flavour"
        }
      ],
      "yeast": "Wyeast 1056 - American Ale\u2122"
    },
    "food_pairing": [
      "Spicy chicken tikka masala",
      "Grilled chicken quesadilla",
      "Caramel toffee cake"
    ],
    "brewers_tips": "The earthy and floral aromas from the hops can be overpowering. Drop a little Cascade in at the end of the boil to lift the profile with a bit of citrus.",
    "contributed_by": "Sam Mason <samjbmason>"
  },
  {
    "id": 2,
    "name": "Trashy Blonde",
    "tagline": "You Know You Shouldn't",
    "first_brewed": "04\/2008",
    "description": "A titillating, neurotic, peroxide punk of a Pale Ale. Combining attitude, style, substance, and a little bit of low self esteem for good measure; what would your mother say? The seductive lure of the sassy passion fruit hop proves too much to resist. All that is even before we get onto the fact that there are no additives, preservatives, pasteurization or strings attached. All wrapped up with the customary BrewDog bite and imaginative twist.",
    "image_url": "https:\/\/images.punkapi.com\/v2\/2.png",
    "abv": 4.1,
    "ibu": 41.5,
    "target_fg": 1010,
    "target_og": 1041.7,
    "ebc": 15,
    "srm": 15,
    "ph": 4.4,
    "attenuation_level": 76,
    "volume": {
      "value": 20,
      "unit": "liters"
    },
    "boil_volume": {
      "value": 25,
      "unit": "liters"
    },
    "method": {
      "mash_temp": [
        {
          "temp": {
            "value": 69,
            "unit": "celsius"
          },
          "duration": null
        }
      ],
      "fermentation": {
        "temp": {
          "value": 18,
          "unit": "celsius"
        }
      },
      "twist": null
    },
    "ingredients": {
      "malt": [
        {
          "name": "Maris Otter Extra Pale",
          "amount": {
            "value": 3.25,
            "unit": "kilograms"
          }
        },
        {
          "name": "Caramalt",
          "amount": {
            "value": 0.2,
            "unit": "kilograms"
          }
        },
        {
          "name": "Munich",
          "amount": {
            "value": 0.4,
            "unit": "kilograms"
          }
        }
      ],
      "hops": [
        {
          "name": "Amarillo",
          "amount": {
            "value": 13.8,
            "unit": "grams"
          },
          "add": "start",
          "attribute": "bitter"
        },
        {
          "name": "Simcoe",
          "amount": {
            "value": 13.8,
            "unit": "grams"
          },
          "add": "start",
          "attribute": "bitter"
        },
        {
          "name": "Amarillo",
          "amount": {
            "value": 26.3,
            "unit": "grams"
          },
          "add": "end",
          "attribute": "flavour"
        },
        {
          "name": "Motueka",
          "amount": {
            "value": 18.8,
            "unit": "grams"
          },
          "add": "end",
          "attribute": "flavour"
        }
      ],
      "yeast": "Wyeast 1056 - American Ale\u2122"
    },
    "food_pairing": [
      "Fresh crab with lemon",
      "Garlic butter dipping sauce",
      "Goats cheese salad",
      "Creamy lemon bar doused in powdered sugar"
    ],
    "brewers_tips": "Be careful not to collect too much wort from the mash. Once the sugars are all washed out there are some very unpleasant grainy tasting compounds that can be extracted into the wort.",
    "contributed_by": "Sam Mason <samjbmason>"
  },
  {
    "id": 3,
    "name": "Berliner Weisse With Yuzu - B-Sides",
    "tagline": "Japanese Citrus Berliner Weisse.",
    "first_brewed": "11\/2015",
    "description": "Japanese citrus fruit intensifies the sour nature of this German classic.",
    "image_url": "https:\/\/images.punkapi.com\/v2\/keg.png",
    "abv": 4.2,
    "ibu": 8,
    "target_fg": 1007,
    "target_og": 1040,
    "ebc": 8,
    "srm": 4,
    "ph": 3.2,
    "attenuation_level": 83,
    "volume": {
      "value": 20,
      "unit": "liters"
    },
    "boil_volume": {
      "value": 25,
      "unit": "liters"
    },
    "method": {
      "mash_temp": [
        {
          "temp": {
            "value": 60,
            "unit": "celsius"
          },
          "duration": 10
        },
        {
          "temp": {
            "value": 65,
            "unit": "celsius"
          },
          "duration": 30
        },
        {
          "temp": {
            "value": 72,
            "unit": "celsius"
          },
          "duration": 10
        },
        {
          "temp": {
            "value": 78,
            "unit": "celsius"
          },
          "duration": 5
        }
      ],
      "fermentation": {
        "temp": {
          "value": 21,
          "unit": "celsius"
        }
      },
      "twist": "Soured naturally using the kettle souring technique, Yuzu fruit: 50g at middle, Yuzu juice: 200ml at FV"
    },
    "ingredients": {
      "malt": [
        {
          "name": "Propino Pale Malt",
          "amount": {
            "value": 1.63,
            "unit": "kilograms"
          }
        },
        {
          "name": "Wheat Malt",
          "amount": {
            "value": 1.63,
            "unit": "kilograms"
          }
        },
        {
          "name": "Propino Pale Malt for kettle 0.03kg souring",
          "amount": {
            "value": 0.03,
            "unit": "kilograms"
          }
        },
        {
          "name": "Acidulated Malt for kettle souring",
          "amount": {
            "value": 0.03,
            "unit": "kilograms"
          }
        }
      ],
      "hops": [
        {
          "name": "Bramling Cross",
          "amount": {
            "value": 10,
            "unit": "grams"
          },
          "add": "middle",
          "attribute": "bitter"
        }
      ],
      "yeast": "Wyeast 1056 - American Ale\u2122"
    }

【问题讨论】:

    标签: ios json swift struct


    【解决方案1】:

    使用optional binding 来避免这个问题

    使用

    if let ibu = item?.ibu {
      labelAmargor.text = "\(String(describing: ibu))" 
    } 
    

    而不是

    labelAmargor.text = "\(String(describing: item!.ibu))" 
    

    【讨论】:

    • 您好,非常感谢您帮助我,伙计!它工作得很好。但是,你看到我的结构了吗?我应该使用可选项还是删除?
    • if let ibu = item?.ibu { 并且不要使用 String(describing:) 方法。 labelAmargor.text = "\(ibu)"
    • @TituJow 你应该使用可选项
    • 那么,我应该在所有属性上添加可选参数吗?
    • 非常感谢@LeoDabus!我很感激
    【解决方案2】:

    我会推荐 Nil-Coalescing Operator ( ?? )。您可以找到详细信息here

    类测试{ var ibu:双倍? }

    var tt: Test? = Test()
    tt?.ibu = 3.14
    print(String(describing: tt?.ibu)) // Optional("3.14")
    print(tt?.ibu ?? 0) // 3.14
    tt?.ibu = nil
    print(String(describing: tt?.ibu)) // nil
    print(tt?.ibu ?? 0) // 0
    

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2020-01-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多