Bonjour, I would like to translate the exercise “Target” from Aaron’s book into a quick one, but I can’t find a solution. Objective'c Code:
@dynamic firstName; @dynamic lastName; @dynamic department; + (NSSet *)keyPathsForValuesAffectingFullName { return [NSSet setWithObjects:@"firstName", @"lastName", nil]; } - (NSString *)fullName { NSString *first = [self firstName]; NSString *last = [self lastName]; if (!first) return last; if (!last) return first; return [NSString stringWithFormat:@"%@ %@", first, last]; }
I found the function in the developer documentation, but I cannot figure out how to implement this code.
to be more explicit this is an apple document
Mutual relations
To automatically trigger notifications for a mutual relationship, you must either override keyPathsForValuesAffectingValueForKey: or implement a suitable method that follows the template that it defines for registering dependent keys.
For example, a person’s full name depends on both the name and the name. A method that returns the full name can be written as follows:
- (NSString *)fullName { return [NSString stringWithFormat:@"%@ %@",firstName, lastName]; }
An application that monitors the fullName property must be notified when the firstName or lastName properties change, since they affect the value of the property.
One solution is to override keyPathsForValuesAffectingValueForKey: indicating that the person’s fullName property depends on the lastName and firstName properties. Listing 1 shows an example implementation of this dependency:
Listing 1 Example implementation of keyPathsForValuesAffectingValueForKey:
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key]; if ([key isEqualToString:@"fullName"]) { NSArray *affectingKeys = @[@"lastName", @"firstName"]; keyPaths = [keyPaths setByAddingObjectsFromArray:affectingKeys]; } return keyPaths; } class func keyPathsForValuesAffectingValueForKey(_ key: String) -> NSSet
Can someone tell me how to implement this function in swift?
Thanks for helping me.