user2452063 user2452063 - 1 month ago 6
JSON Question

Swift Converting Optional String to Int

this seems like a pretty basic question but for some reason haven't been able to get it resolved. I'm using Alamofire to parse JSON and trying to get a header value that tells me my current api rate limit.

if let xRate = String(describing: response.response?.allHeaderFields["X-Ratelimit-Remaining"])as String? {
self.jsonCallsRemaining = xRate
print("json: ", xRate)
print("json2: ", Int(xRate))
}


When trying to get the Int of xRate (or Float, or Double) I get 'nil'. In the consolve i'm seeing:

json: Optional(79)

json2: nil

It appears that the number is coming back as an optional string. Am I missing something obvious? New to Swift. Thanks!

Answer

Maybe, your String.init(describing:) is extraneous and unnecessary.

    if let xRate = response.response?.allHeaderFields["X-Ratelimit-Remaining"] as? String {
        self.jsonCallsRemaining = xRate
        print("json: ", xRate)
        print("json2: ", Int(xRate))
    }
Comments