swiftkvc

Can you run KVC functions in Xcode Playgrounds?


I'm following a tutorial on KVC and KVO when I attempted to enter the code into a playground however it wouldn't run. I received the error "terminating with uncaught exception of type NSException". I even tried to create a single app application and entered the information into a viewController to see what happens and it still wouldn't build which provided the error that the object wasn't key coding compliant. I'd really like to see this work, what am I doing incorrectly?

import UIKit
import Foundation


//this is a reference object which means when it is copied, it will copy a reference to the same instance and not a brand new value like a value type does
class Student: NSObject {
    var name: String = ""
    var gradeLevel: Int = 0
}


let seat1 = Student()
seat1.setValue("Kelly", forKey: "name")

Solution

  • Your issue is not the playground. Your issue is that to use the Objective-C KVC mechanism, you need to mark the property with @objc.

    class Student: NSObject {
        @objc var name: String = ""
        var gradeLevel: Int = 0
    }
    

    Adding that will fix the crash.