MaxKrissigo MaxKrissigo - 2 months ago 149
Swift Question

Swift 3 Firebase - (setValue:) Cannot store object of type _SwiftValue at content

I've seen this question asked multiple times, but can't seem to figure out how to use those answers to solve the problem in my code. This is the current code I'm using:

if let postContent = postAlert.textFields?.first?.text {
let post = Post(content: postContent, addedByUser: "Max Kortge")

let postRef = self.dbRef.child(postContent.lowercased())

postRef.setValue(post.toAnyObject()) //error here
}


I presume that the error in the console means the line where I've commented 'error here'.

The method toAnyObject is below:

func toAnyObject() -> Any {
return ["content":content, "addedByUser":addedByUser] as Any
}


The full console error is below:

Terminating app due to uncaught exception 'InvalidFirebaseData', reason: '(setValue:) Cannot store object of type _SwiftValue at content. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'


Thanks,
Max

Answer

Try changing :-

func toAnyObject() -> Any {
  return ["content":content, "addedByUser":addedByUser] as Any
 }

To

func toAnyObject() -> [AnyHashable:Any] {
  return ["content":content, "addedByUser":addedByUser] as [AnyHashable:Any]
 }