问题
I have implemented a Parse subclass called Filler.swift
that 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