Home > database >  Need to unwrap Int?
Need to unwrap Int?

Time:10-02

I keep getting this error message: Value of optional type 'Int?' must be unwrapped to a value of type 'Int'

with this code:

let data = document.data()

let uid = data["userid"] as? String ?? ""
let location = data["location"] as? String ?? ""
let currentRating = data["currentRating"] as? Int
let usualRating = data["usualRating"] as? Int


var Submission = RatingSubmission(uid: uid, location: location, currentRating: currentRating, usualRating: usualRating)

what do I need to add to currentRating and usualRating in the Submission variable so that it runs properly?

CodePudding user response:

The reason is that RatingSubmission function works with Int values but you if you assign them as optional values there is a chance to these variables may be "nill". To avoid this you can either remove this option like this:

let currentRating = data["currentRating"] as? Int ?? 0
let usualRating = data["usualRating"] as? Int ?? 0

Second option, if you sure these values are not nill, you can downcasting using "as!".(this is not safe most time)

let currentRating = data["currentRating"] as! Int
let usualRating = data["usualRating"] as! Int

Third option, you can check the values with if let;

let currentRating = data["currentRating"] as? Int
let usualRating = data["usualRating"] as? Int
if let currentRating = Int(data["currentRating"]), let usualRating = Int(data["usualRating"]) {
var Submission = RatingSubmission(uid: uid, location: location, currentRating: currentRating, usualRating: usualRating)
}

CodePudding user response:

I would recommend using the get() method on the document which was made specifically for getting properties from documents.

if let usualRating = document.get("usualRating") as? Int {
    print(usualRating)
}

Alternatively, you can one-line it by giving it a default value (of 0 in this case). But this would appear like an anti-pattern to me just on the face of it.

let usualRating = document.get("usualRating") as? Int ?? 0
  • Related