Uploaded image for project: 'Swift'
  1. Swift
  2. SR-4559

Method called 'self' can be confused with regular 'self'

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler
    • Labels:
      None
    • Environment:

      macOS 10.12.4, Xcode 8.3.1

      Description

      This compiles because instance method `self` is accessible as a static member: `self`(_ self: TypeWithSelfMethod) -> () -> Void

      func funcThatReturnsSomething(_ any: Any) -> Any {
          any
      }
      
      struct TypeWithSelfMethod {
          
          let property = self
          
          let propertyFromClosure: () = {
              print(self)
          }()
          
          let propertyFromFunc = funcThatReturnsSomething(self)
          
          func `self`() {
              
          }
      }
      

      This is particularly problematic as NSObject has a method with this name, so code to add target is compiling and doesn't refer to the self the user likely expects

      import UIKit
      
      class A: NSObject {
      
        private let control: UIControl = {
          let control = UIControl()
          control.addTarget(self, action: #selector(valueChanged), for: .valueChanged)
          return control
        }()
      
      
        @objc private func valueChanged() {
      
        }
      }
      

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              mouhcine Mouhcine El Amine
              Reporter:
              mouhcine Mouhcine El Amine
              Votes:
              8 Vote for this issue
              Watchers:
              18 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: