Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-9498] Observing an object's protocol crashes, while observing the object directly works #3573

Open
swift-ci opened this issue Dec 12, 2018 · 2 comments

Comments

@swift-ci
Copy link
Contributor

Previous ID SR-9498
Radar None
Original Reporter JeffreyEarly (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Foundation
Labels Bug, KeyPaths
Assignee None
Priority Medium

md5: 1848302fc9a5554dbe3251cbc7003e87

Issue Description:

It looks like you can not observe NSObjects with protocols, even if the underlying class can be observed directly.

import Foundation

protocol Enabled {
    var isEnabled: Bool {get set}
}

class C: NSObject, Enabled {
    @objc dynamic var isEnabled: Bool = false
}

let c = C()

func observeMeDirectly(_ object: C) {
    let _ = object.observe(\.isEnabled, options: [.new]) { _, _ in
        print("changed")
    }
}

observeMeDirectly(c)
// this works fine

func observeMyProtocolType<T>(_ object: T) where T:Enabled, T:NSObject {
    let _ = object.observe(\.isEnabled, options: [.new]) { _, _ in
        print("changed")
    }
}

observeMyProtocolType(c)
// this fails

This looks different than the other related bugs I've found in the tracker, but I'm not sure.

@belkadan
Copy link

I think this is correct behavior because the protocol's property isn't @objc. That is, someone else could implement the protocol and subclass NSObject without exposing the property to Objective-C. You can make the protocol @objc to fix this.

Leaving open to potentially improve the error message:

Fatal error: Could not extract a String from KeyPath Swift.WritableKeyPath<main.C, Swift.Bool>: file /Volumes/Data/swift-public/swift/stdlib/public/SDK/Foundation/NSObject.swift, line 91

@swift-ci
Copy link
Contributor Author

Comment by Jeffrey J. Early (JIRA)

Yes, that makes perfect sense. Thank you.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
@shahmishal shahmishal transferred this issue from apple/swift May 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants