调用Swift函数

时间:2017-04-27 18:52:55

标签: swift xcode firebase

let imageOne = images[0] as! UIImage
let imageTwo = images[1] as! UIImage

我有一个功能

    func uploadImage(image: UIImage){
                                        let randomName = randomStringWithLength(length: 5)
                                        let randomNames = randomStringWithLength(length: 9)
                                        let imageData = UIImageJPEGRepresentation(imageOne, 1.0)
                                        let imageDatas = UIImageJPEGRepresentation(imageTwo, 1.0)
                                        let uploadRef = FIRStorage.storage().reference().child("images/\(randomName).jpg")


                                        let uploadTask = uploadRef.put(imageData!, metadata: nil) { metadata,
                                            error in
                                            if error == nil {
                                                print("successfully uploaded Image")
                                                AppDelegate.instance().dismissActivityIndicator()
                                                self.imageFileName = "\(randomName as String).jpg"


                                        let uploadTaskTwo = uploadRef.put(imageDatas!, metadata: nil) { metadata,
                                                        error in
                                                        if error == nil {
                                                            self.imageFileNameTwo = "\(randomNames as String).jpg"
                                                        }

                                                let postObject: Dictionary<String, Any> = [
                                                    "imageOne" : self.imageFileName,
                                                    "imageTwo" : self.imageFileNameTwo,



                                                ]
}}else{
print("Error  uploading image")
}

我想调用具有多个图像的功能。

    if let pickedImage = ((imageOne as? UIImage) != nil), ((imageTwo as? UIImage) != nil) {
    uploadImage(image: pickedImage)                                          
}

但我不断收到错误“条件绑定的初始化程序必须具有可选类型,而不是'Bool'。请帮助我。

2 个答案:

答案 0 :(得分:0)

为什么使用可选绑定来检查nil

 if let variable` = optional var {}

上述语义表示如果optional var具有某些值,则会将其分配给variable

现在回答你的问题,

  if let pickedImage = ((imageOne as? UIImage) != nil) {
  }

在您的情况下,如果imageOne as? UIImage不是nil,那么它将被分配到pickedImage,但此表达式((imageOne as? UIImage) != nil)Bool类型。

如果您需要检查nil值,那么您应该只使用if

  let pickedImage = imageOne as? UIImage
  if pickedImage != nil {
  }

此外,我建议您阅读Apple documentation

答案 1 :(得分:0)

您可以使用nil-coalescing运算符ControlGUIDs

??

零合并算子a ?? b是

的快捷方式
     var test1: String? = "Test1" // in your code imageOne
     var test2: String? = nil // and imageTwo

     if let test = test1 ?? test2 {
         print(test) // Output: "Test1"
     }

它返回左操作数解包或右操作数。

相关问题