简体   繁体   中英

Code runs fine on Playground; at the same time it yields an EXC_I386_GPFLT error

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.

This isn't an answer really but a workaround till I figure out why this works:

let andy = Anilist()
let someVar = andy.user.me { results in
    print(results)
}

This gives a compile time warning saying constant someVar inferred to have type (), which maybe unexpected .

But doing this:

let andy = Anilist()
let _ = andy.user.me { results
    print(results)
}

works fine WITHOUT any errors at all. Weird enough. It'd be really good if someone could explain why this happens.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM