I'm having this curious issue in which a Playground prints the expected result but at the same time I see an error telling me the execution was stopped because of an EXC_I386_GPFLT
error.
I'm using a Playground to model how should an API wrapper I'm writing be used. The idea of doing this is to plan a nice API for future developers.
The following is the entire "planning" code I have written to plan out my wrapper. Feel free to copy and paste it on a Playground to see the problem in action:
class Anilist {
init() {}
internal class UserAPIs {
weak var parent: Anilist? = nil
init(parent: Anilist) {
self.parent = parent
}
}
lazy var user: UserAPIs = { [unowned self] in
let userapi = UserAPIs(parent: self)
return userapi
}()
}
extension Anilist.UserAPIs {
func me(_ completionHandler: (results: [String]) -> Void ) {
// Do some logic, fetching stuff from parent
completionHandler(results: ["Lorem", "Sammet"])
}
}
let andy = Anilist()
andy.user.me { results in
print(results)
}
Curiously, it prints ["Lorem", "Sammet"]
properly, but at the same time I get that error.
I have read (for C++) a few other questions regarding this error but unfortunately I haven't been able to solve this issue. For what I can gather is this is happening because I'm attempting to access memory that is nil? In general, I haven't been able to find much information regarding this other than it being an architecture protection.
While the code runs fine, I'm hesitant about putting this on my actual code yet, as I have no idea how it would behave. Even if it works on the first run, it's hard to predict if it will produce errors in the long run.
EDIT:
It looks like it has something to do with the calculated lazy var
. Changing that line to this:
lazy var user: UserAPIs = UserAPIs(parent: self)
Works as expected (as in, it prints the array and doesn't give me the EXC_I386_GPFLT
error).
EDIT 2:
Previous edit seems to be inaccurate information.