I'm trying to query for the token and user_id from my realm database and then pass to my private var token and userId but I keep getting thrown this error
Unexpected non-void return value in void function
at return particular.id
and
Cannot assign value of type '()' to type 'Int!'
at _userId = getId()
This is my code:
import Foundation
import RealmSwift
class Users {
private var _userId: Int!
private var _token: String!
var userId: Int {
_userId = getId()
return _userId
}
func getId () {
guard let userName = Data.sharedInstance.userName else { print("Empty username"); return }
do {
let realm = try Realm()
if let particular = realm.objects(Particulars).filter("username == '\(userName)'").first {
return particular.id
}
} catch let error as NSError {
// handle error
print(error)
}
}
}
So there are two things that I want to know:
Your function is defined as func getId ()
which means it doesn't return a value. Then you try and return something at return particular.id
. You need to change your function definition to func getId() -> Int?
and then also add a return nil
as the last line for when your fetch fails (same for your guard
statement).
Of course, you'll also have to handle that nil
value when calling getId()
in the var userId
, or change userId
to be optional as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.