Skip to content

[SR-6895] Timer property with initializer and self target causes crash at runtime #49444

@mattneub

Description

@mattneub
Previous ID SR-6895
Radar None
Original Reporter @mattneub
Type Bug
Status Resolved
Resolution Duplicate
Environment

Swift 4.1, Xcode 9.3 beta 1

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

md5: b788bbb198c95ec64db19b32b0652bd1

duplicates:

Issue Description:

I thought I had raised this issue before, but now I see that I never made it explicit, so I'd like this code on the record:

class ViewController: UIViewController {
    var timer : Timer? = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerFired), userInfo: nil, repeats: true)
    @objc func timerFired(_ : Timer) {
        print("fired")
    }
}

That code is legal (the compiler doesn't complain) but causes a crash at runtime. The reason seems to be that the self referred to as the target is not the view controller (presumably because our object is not fully formed the time we are initializing properties).

This is a very common trap for beginners to fall into. The compiler should disallow this use of self.

This may be a duplicate of #47442 but I was not so explicit there about the Timer problem, which is the common use case that bites everyone.

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