KVC:
Key-Value-Coding is a mechanism to retrieve Object's property directly by name rather than retrieving by instance of object
This mechanism implemented by NSCoding protocol at the era of Objective-C over NS objects
In Swift this mechanism is still available but only if it's derived from NS objects or conform to NSCoding protocol
Most of Foundation and core(NS objects ) are conform to NSCoding except UIImage!
class Flight {
var aircraft:String
init() {
aircraft = "Boeing 747"
}
}
var flight:Flight = Flight()
flight.setValue("Airbus 380", forKey:"aircraft") // error-not working!
Now we change it to following :
class Flight : NSObject{
var aircraft:String
init() {
aircraft = "Boeing 747"
}
}
var flight:Flight = Flight()
flight.setValue("Airbus 380", forKey:"aircraft") // Ok, It works!
now suppose we have:
class Flight : NSObject{
var aircraft:String
var passengerCount:Int? = 0
var maxPassengerCount:Int = 0
init() {
aircraft = "Boeing 747"
}
}
var flight:Flight = Flight()
flight.setValue("Airbus 380", forKey:"aircraft")
flight.setValue(400, forKey:"passengerCount") // error,field cannot be optional
flight.setValue(800, forKey:"maxPassengerCount") //ok!,field is not optional