Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value(forKey:) for NSObject not working in Swift 4

Tags:

swift

swift4

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).
like image 947
closetCoder Avatar asked Jun 09 '17 15:06

closetCoder


2 Answers

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

like image 105
Sulthan Avatar answered Sep 21 '22 16:09

Sulthan


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

like image 31
Code Different Avatar answered Sep 19 '22 16:09

Code Different