代码之家  ›  专栏  ›  技术社区  ›  user1904273

将字符串设置为可选,并在swift中设置为默认值(如果为零)

  •  -3
  • user1904273  · 技术社区  · 6 年前

    如果字符串存在,以下代码将显示一个图像:

     if let contact = notification.userInfo?["contact"] as? Contacts,
                let pic = contact.pic  {
                 if let img = self.loadImageNamed(pic) {
    //Display the image
    }
    }
    

    然而,我正在努力使用语法来检测丢失的字符串并显示默认图像。

    pic不是可选的。

    if let contact = notification.userInfo?["contact"] as? Contacts,
                    let pic? = contact.pic ?? "default.pic"  {
                     if let img = self.loadImageNamed(pic) {
        //Display the image
    }
    } 
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   vadian    6 年前

    几乎, pic 是非可选的,它不能位于可选绑定表达式中

    if let contact = notification.userInfo?["contact"] as? Contacts {
       let pic = contact.pic ?? "default.pic"  
       if let img = self.loadImageNamed(pic) {
           //Display the image
       }
    }
    
        2
  •  1
  •   Sulthan    6 年前

    另一种可能性是使用可选链接

    let pic = (notification.userInfo?["contact"] as? Contacts)?.pic
    let img = self.loadImageNamed(pic ?? "default.pic") 
    

    或者,如果 pic 可以是空字符串:

    let pic = (notification.userInfo?["contact"] as? Contacts)?.pic ?? ""
    let img = self.loadImageNamed(!pic.isEmpty ? pic : "default.pic")