iOS - Swift and Parse error regarding Optionals within Subclass

你说的曾经没有我的故事 提交于 2020-01-06 14:03:37

问题


I have implemented a Parse subclass called Filler.swiftthat contains five variables that are held in the Parse backend.

Whilst trying to save data to the Parse backend using this subclass I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value.

This is the code that brings about the error (on the self.object.username = username line):

if let username = PFUser.currentUser()?.username {

        // set username equal to current user
        self.object.username = username

    }else{

        println("PFUser.currentUser()?.username contained a nil value.")

    }

I've figured out that it's something to do with how I'm handling optional variables in my subclass but the Parse documentation isn't clear on exactly how to do this. Here's my code for the subclass:

class Fillup : PFObject, PFSubclassing {

var amount : String? {

    get {

        return self["amount"] as? String

    }

    set{

        self["amount"] = newValue

    }

}

var cost : String? {

    get {

        return self["cost"] as? String

    }

    set{

        self["cost"] = newValue

    }

}


var date : NSDate {

    get {

        return self["date"] as! NSDate

    }

    set{

        self["date"] = newValue

    }

}

var username: String? {

    get{

        return self["username"] as? String

    }

    set {


        self["username"] = newValue

    }
}


var id : Int?{

    get {

        return self["id"] as? Int

    }

}

override class func initialize() {

    var onceToken : dispatch_once_t = 0;

    dispatch_once(&onceToken) {

        self.registerSubclass()

    }

}

class func parseClassName() -> String {

    return "Fillup"
}

}

Any help would be really appreciated.


回答1:


Did you try adding a ? like so: self.object?.username = username



来源:https://stackoverflow.com/questions/29976439/ios-swift-and-parse-error-regarding-optionals-within-subclass

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