J. Doe
J. Doe

Reputation: 285

Expression type '@lvalue String?' is ambiguous without more context

Out of nothing I got this error Expression type '@lvalue String?' is ambiguous without more context in my code:

    if textView.text != "" && takenImage != nil && userLocation.text != "" {
        checkInternet()
        // Create and save a new job
        let newJob = Job(text: textView.text, jobImage: takenImage!, addedByUser: (userLabel?.text)!(-> ERROR), userImage: UserImage, location: userLocation.text, passMap: takenLocation, userID: userID, postID: key)
        newJob.save()
    } 

I tried to solve it with answers from other question, but I didn't got it working...

Job Class:

var text: String = ""
var location: String = ""
var map: String?
var passMap: String?
var addedByUser: String?
var userImage: UIImage?
var jobImage: UIImage?
var downloadURL: String?
var userDownloadURL: String?
var numberOfLikes = 0
var numberOfDislikes = 0
let ref: DatabaseReference!
var userID: String?
var postID: String?


init(text: String? = nil, jobImage: UIImage? = nil, addedByUser: String? = nil, userImage: UIImage? = nil, location: String? = nil, passMap: String? = nil, userID: String? = nil, postID: String? = nil, data: [String : Any]) {
    self.text = text!
    self.jobImage = jobImage
    self.addedByUser = addedByUser
    self.userImage = userImage
    self.location = location!
    self.passMap = passMap
    self.userID = userID
    self.postID = postID
    ref = Database.database().reference().child("jobs").childByAutoId()
}

Upvotes: 0

Views: 268

Answers (2)

PGDev
PGDev

Reputation: 24341

In the code above,

  1. Use userLabel?.text directly without unwrapping anything. addedByUser is of type String?.

  2. You're using UserImage type for userImage parameter. Use a UIImage instance or nil instead.

  3. You haven't added data parameter in your code.

Here is the code,

let newJob = Job(text: textView.text, jobImage: takenImage, addedByUser: userLabel?.text, userImage: nil, location: userLocation.text, passMap: takenLocation, userID: userID, postID: key, data: [:])

Avoid unnecessarily force-unwrap the optionals. It might result in runtime exception.

Upvotes: 1

CZ54
CZ54

Reputation: 5588

Two things are wrong:

textView.text != "" You are comparing an optional String with a non-optional one.

Replace by:

if let text = textView.text, text != ""

Then in your constructor, don't unwrap the text!

If you want keep the optional :

self.text = text ?? "" //will avoid crash

Or better:

init(text: String = "")

Upvotes: 1

Related Questions