O'Reilly logo

Mastering Swift 4 - Fourth Edition by Jon Hoffman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the self keyword

Since Swift does not require us to use the self keyword when accessing properties or invoking methods of an object, we should avoid using it unless we need to distinguish between an instance property and local variables. Here is an example of when you should use the self keyword:

public class EmployeeClass {  
  var firstName = "" 
  var lastName = "" 
  func setName(firstName: String, lastName: String) {  
    self.firstName = firstName 
    self.lastName = lastName 
  } 
} 

Here is an example of when not to use the self keyword:

public class EmployeeClass {  
  var firstName = "" 
  var lastName = "" 
  func getFullName() -> String { 
    return self.firstName + " " + self.lastName 
  } 
} 

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required