Value sometimes returns as optional string with SwiftyJSON

霸气de小男生 提交于 2019-12-13 03:01:18

问题


I wonder why the SwiftyJSON sometimes returns a value as "myString" and some other time as Optional("myString")

For example:

func getFBUserData(){
        if((FBSDKAccessToken.currentAccessToken()) != nil){
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
                if (error == nil){

                    let fbJson = JSON(result)
                    let fbId = fbJson["id"].string
                    print(fbId)
                }
            })
        }
    }

Here fbId will return: Optional("myString")

Next:

static func loginWithEmail(facebookId: String, email: String, username: String, response: (token: String?) -> ()) {
        let urlString = baseURL + ResourcePath.FbLogin.description

        let parameters: [String: AnyObject] = [
            "fb_id": facebookId,
            "level": 1,
            "email": email,
            "username": username
        ]
        Alamofire.request(.POST, urlString, parameters: parameters).responseJSON{ (responseData) -> Void in
            //print(responseData)
            let json = JSON(responseData.result.value!)
            let token = json["api_token"].string
            response(token: token)
        }

    }

Here token will return "myString"

So how can one function return optional() when both functions use ".string" and not ".string!"?


回答1:


SwiftyJSON has two kinds of "getters" for retrieving values: Optional and non-Optional.

.string is the optional getter for the String representation of a value, so you have to unwrap it before use

if let fbId = fbJson["id"].string {
    print(fbId)
}

otherwise the String itself will contain the term "Optional".

If you are 100% sure that there will always be a value, you can use the equivalent of "force unwrap" by using the non-Optional getter and you don't need if let anymore:

let fbId = fbJson["id"].stringValue

But beware because this will crash if the value is nil, exactly as if you were force-unwrapping with fbJson["id"].string! (which you should never do).

Note that SwiftyJSON works the same for the other types: .int vs .intValue, .array vs .arrayValue, etc.




回答2:


! is dangerous especially when you don't know if it is optional.Just do like this:

func getFBUserData(){
        if((FBSDKAccessToken.currentAccessToken()) != nil){
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
                if (error == nil){

                    let fbJson = JSON(result)
                    if let fbId = fbJson["id"].string {
                        print(fbId)
                    }
                }
            })
        }
    }



回答3:


That is because you are doing this let fbJson = JSON(result) instead of let fbJson = JSON(result!)



来源:https://stackoverflow.com/questions/36346496/value-sometimes-returns-as-optional-string-with-swiftyjson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!