如何从UILabel删除可选文本

时间:2018-07-18 04:47:09

标签: ios json swift struct

我正在尝试在运行应用程序时删除<xsl:output method="xml" indent="yes"/> <xsl:template match="Transactions"> <xsl:for-each-group select="*" group-starting-with="Number[ position() mod 2 = 1]"> <TransactionDetail> <xsl:copy-of select="current-group()"/> </TransactionDetail> </xsl:for-each-group> </xsl:template> Try it 上的Optional文本。但是,我已经尝试了许多方法,UILabel仍然存在。

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

  

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

我该如何解决?

应用图片: Postman console

模型文件夹:

JSONDecoder

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

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

JSON:

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

        }
}

2 个答案:

答案 0 :(得分:2)

使用optional binding可以避免此问题

使用

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

代替

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

答案 1 :(得分:0)

我建议使用Nil-Coalescing运算符(??)。您可以找到详细信息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
相关问题