Skip to content

[SR-7198] Using self in computed let #49746

@swift-ci

Description

@swift-ci
Previous ID SR-7198
Radar None
Original Reporter nrbrook (JIRA User)
Type Bug
Status Resolved
Resolution Duplicate

Attachment: Download

Environment

Xcode Version 9.2 (9C40b)

Swift 4

Additional Detail from JIRA
Votes 0
Component/s
Labels Bug
Assignee None
Priority Medium

md5: 04555a2ce1020475bcf49a13514222fd

duplicates:

Issue Description:

See the attached project, relevant code here:

class Test: UIButton {
    var test = 0
    
    override func addTarget(_ target: Any?, action: Selector, for controlEvents: UIControlEvents) {
        print("\(String(describing: target))")
        super.addTarget(target, action: action, for: controlEvents)
    }
}

class ViewController: UIViewController {
    let test: Test = {
        let b = Test(type: .system);
        b.addTarget(self, action: #selector(ViewController.changed), for: UIControlEvents.touchUpInside)
        return b
    }()
    
    @objc func changed() {
        print("Hello pressed!")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let s = self.test
        s.setTitle("Hello", for: .normal)
        s.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        self.view.addSubview(s)
    }
}

If you run this and press the button it will print:

Optional((Function))
Hello pressed!

If you put a breakpoint in Test.addTarget and when hit run po target! in lldb, continue, then press the button, you get a crash: unrecognized selector sent to instance

The behaviour of this code is, I believe, undefined. Should self be the closure, in which case the crash should occur every time, or should this generate a compiler error as self is not valid in this context?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfdiagnostics QoIBug: Diagnostics Quality of ImplementationexpressionsFeature: expressionsidentifiersFeature: Identifiersmissing warningBug: Missing warningselfFeature → expressions: The 'self' expressionswift 5.6type checkerArea → compiler: Semantic analysis

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions