I’ve the next code that at all times returns an occasion of Member
, when it ought to be returning nil
. It doesn’t matter what I enter for username
, and regardless of what number of occasions I delete the app from the simulator, the throw
is at all times triggered from the create
operate.
class MemberViewModel: ObservableObject {
...
func create() throws -> Void {
let context = Self.container.viewContext
if entity!.username != nil {
if attempt Self.fetch(username: entity!.username!) != nil {
throw MemberError.UserExists(username: entity!.username!)
}
if context.hasChanges {
attempt context.save()
}
}
}
static non-public func fetch(username: String) throws -> Member? {
let fetchRequest: NSFetchRequest<Member> = Member.fetchRequest()
let context = Self.container.viewContext
fetchRequest.predicate = NSPredicate(format: "username[c] == %@", username)
return attempt? context.fetch(fetchRequest).first
}
...
}
extension MemberViewModel {
public enum MemberError: Error {
case UserExists(username: String)
}
}
The calling code seems like:
extension MemberView {
func save() -> Void {
if (identify.isEmpty) {
nameError = "A reputation should be offered to proceed"
}
if (username.isEmpty) {
usernameError = "A username or e-mail should be offered"
}
if (nameError != nil || usernameError != nil) {
return
}
do {
let mvm = MemberViewModel(identify: identify, username: username, password: password, age: age, position: position, admin: admin, imageName: AVATARS[selectedImage], imageTint: selectedTint)
attempt mvm.create()
web page = nil
} catch MemberViewModel.MemberError.UserExists(let username) {
usernameError = "The username (username) is already taken"
} catch {
}
}
}