Return statement in nested if function

时间:2015-11-26 11:14:34

标签: ios swift

I have been struggling with something for a while. How can I return something in a nested if function? The function below has the task of finding out if the userProfile has a verified card or not, if verified == 1 (true) then return true, else return false.

func userHasVerfifiedCard() -> Bool{
    let userDocument    =   users.documentWithID(Meteor.userID!)
    if let card         =   userDocument.valueForKey("profile")!["card"] {
        print("has card")
        if let verified = card!["verified"] as? Int {
            print("card.verified as Int")

            if verified == 1{
                print("card.verified == 1")
                lastFourCreditCardLbl.text = card!["last4"] as? String
                return true
            }else {
                return false

            }
        }
    }

2 个答案:

答案 0 :(得分:2)

如果if let card不起作用,您的方法将不会返回任何内容。但无论如何它必须返回一个bool。

func userHasVerfifiedCard() -> Bool {
    let userDocument    =   users.documentWithID(Meteor.userID!)
    if let card         =   userDocument.valueForKey("profile")!["card"] {
        print("has card")
        if let verified = card!["verified"] as? Int {
            print("card.verified as Int")

            if verified == 1 {
                print("card.verified == 1")
                lastFourCreditCardLbl.text = card!["last4"] as? String
                return true
            }
        }
    }
    return false
}

答案 1 :(得分:0)

尝试这个,让我知道它是否有帮助..!

func userHasVerfifiedCard() -> Bool{
        let userDocument    =   users.documentWithID(Meteor.userID!)
        if let card         =   userDocument.valueForKey("profile")!["card"], verified = card!["verified"] as? Int where verified == 1 {
            return true
        } else {
            return false
        }
    }