Hi all, when I tried to practice with keypath in Swift, I faced with the error(on Xcode 10.2; Xcode 10.1 have same error):
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
The error appear more than 99%(on Xcode 10.2), rarely it can run Ok but with strange result (really strange behaviour ). The code is:
//KEY PATH
class DebugPrinter<T> where T: AnyObject {
var keyPaths: [(String?, KeyPath<T, Any?>)] = []
let reference: T
let prefix: String
init(_ prefixString: String, for instance: T) {
reference = instance
prefix = prefixString
}
func addLog(_ path: KeyPath<T, Any?>, prefix: String? = nil) {
keyPaths.append((prefix, path))
}
func log() {
print(prefix, terminator: ": ")
for entry in keyPaths {
if let prefix = entry.0 {
print(prefix, terminator: "")
}
print(reference[keyPath: entry.1], terminator: ", ")
}
}
}
import UIKit
class Presentation {
class Slide {
var name: String?
var number: Int?
var backgroundColor: UIColor?
var content: String?
var leftImage: UIImage?
var rightImage: UIImage?
}
var currentSlide: Slide?
var currentSlideIndex: Int?
var slides: [Slide]?
var title: String?
var startedPresenting: Date?
var isAnimating: Bool?
}
let state = Presentation() // we need a presentation instance
let printer = DebugPrinter("State", for: state)
printer.addLog(\Presentation.currentSlideIndex?, prefix: "Current")
printer.addLog(\Presentation.currentSlide?.name)
printer.log()
And I also have another question is that:
Why I have error Key path value type 'Int?' cannot be converted to contextual type 'Any?'
when change the line:
printer.addLog(\Presentation.currentSlideIndex?, prefix: "Current")
To
printer.addLog(\Presentation.currentSlideIndex, prefix: "Current")
.