Search code examples
swiftcompiler-errorsswiftuiuuid

SwiftUI - Error when calling UUID().uuidString id


I get this error EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) when I try to use a function like this:

func itemId(title: String) -> String {
    var id = UUID()
    for item in itemsCoreData {
        if item.title == title {
            id = item.id
        } else {
            break 
        }
    }
    return id.uuidString
}

itemsCoreData is a variable from a fetch request that stores my Core Data objects. item.id is the UUID stored in Core Data of that Object


Solution

  • You just need to use first(where:) method here.

    func itemId(title: String) -> String? {
        itemsCoreData.first(where: { $0.title == title })?.id.uuidString
    }