im working in ios swift, here i have used core data to store values and written some function to find the data and return it.
public func insertdetails (id:String, data:String, createdAt:String){
do{
try self.userdetails.operation { (context, save) throws -> Void in
let model : User = try! context.create()
model.id = id
model.details = data
model.createdat = createdAt
save()
}
}
}
public func fetchdetails (Id:String) -> String{
do {
let predicate: NSPredicate = NSPredicate(format: "id == %@", Id)
let record: User = try! self.userdetails.fetch(FetchRequest<User>().filtered(with: predicate)).first ?? "" // **here im getting error**
return record.details ?? ""
}
}
in 1st code it represent object model.
In 2nd code im facing error.
im getting error as connot convert value of type string to expected argument type User, even if i forcewrap it , suppose value is not present, app gets crash. how to provide the default value in fetch operation.
2
Answers
The error occurs because
first
returns aUser
which is not related to an empty string.And attach the predicate to the fetch request. Core Data filters the records on your behalf.
Your fetch request will return an array of
User
objects but you have a string on the right hand side of then nil coalescing operator; that is why you have an error.You can’t use a string as a replacement for a
User
. You probably don’t want a nil coalescing operator here. Just handle the optional.It is probably nicer if the function itself returns an optional string. Swift optionals are intended to replace sentinel values, such as the empty string you are using here.