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

Method requirements

A protocol can require that the conforming class or structure provides certain methods. We define a method within a protocol exactly as we do within a class or structure, except without the curly braces or method body. Let's add a getFullName() method to our FullName protocol and Scientist class.

protocol FullName {  var firstName: String { get set }  var lastName: String { get set }  func getFullName() -> String 
} 

Now, we will need to add a getFullName() method to our Scientist class so that it will conform to the protocol:

class Scientist: FullName {  
  var firstName = "" 
  var lastName = ""  
  var field = "" 
 
  func getFullName() -> String { 
    return "\(firstName) \(lastName) studies \(field)" 
  } 
} 

Structures can conform to Swift ...

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