9

Trying out Swift 4 in Xcode 9 Beta.

For some reason I'm getting a crash when using key value accessors on an NSObject.

Any ideas?

import Cocoa class Person: NSObject { var name = "" var age = 0 } let alpha = Person() alpha.name = "Robert" alpha.age = 53 alpha.value(forKey: "name") // error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). 
9
  • Related: How can I deal with @objc inference deprecation with #selector() in Swift 4? Commented Jun 9, 2017 at 15:38
  • If you call value(forKey:) with #keyPath(Person.name) instead of a string then the compiler will show a proper error message and Fix-it! Commented Jun 9, 2017 at 15:39
  • 1
    Or even, now that you're in Swift 4, use Swift's key-value coding mechanism print(alpha[keyPath: \Person.name]) :) Then you don't have to inherit from NSObject and can even make Person a struct. Commented Jun 9, 2017 at 15:50
  • I'm using key-value coding in order to dynamically select the property to access from a string variable. Is there any way to do this using the new Swift 4 mechanism? Commented Jun 9, 2017 at 15:56
  • @closetCoder You can store and pass about key paths, e.g let name = \Person.name, but they're not strings (they're strongly typed instead). Strings are such weak types to represent key-paths, and should really be avoided unless absolutely necessary. What's your use case for using a string key path? Commented Jun 9, 2017 at 16:01

2 Answers 2

25

Key-value coding requires Objective-C. In Swift 4 you have to mark members accessible from Obj-C explicitly:

@objcMembers class Person: NSObject { 

or

class Person: NSObject { @objc var name = "" var age = 0 } 

See Swift Evolution 160

Sign up to request clarification or add additional context in comments.

Comments

7

ObjC inference has been limited in Swift 4. You can mark your class with objcMembers for the compiler to generate ObjC-compliant accessors:

@objcMembers class Person: NSObject { var name = "" var age = 0 } 

Or get back the old behavior by setting Swift 3 Objc Inference to On in Build Settings:

enter image description here

1 Comment

Note that the "Swift 3 @objc Inference" build setting is only really there to assist with the migration, and therefore isn't a permanent solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.