Skip to content

Instantly share code, notes, and snippets.

@adilanchian
Created February 22, 2018 00:05
Show Gist options
  • Save adilanchian/4624b51d5966addc580891e2157c24c7 to your computer and use it in GitHub Desktop.
Save adilanchian/4624b51d5966addc580891e2157c24c7 to your computer and use it in GitHub Desktop.
import UIKit
/*
Protocol Definition: A protocol defines a blueprint of methods, properties, and other requirements that suit a particular
task or piece of functionality.
(https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html)
*/
/*
This protocol, GreetFriendDelegate, requires any conforming type to have an instance method called greetFriend, which
returns a String value whenever it’s called
*/
protocol GreetFriendDelegate {
func greetFriend() -> String
}
/*
This is the initial view controller. I want to navigate to my FriendViewController and have Liam greet me!
*/
class MeViewController: UIViewController, GreetFriendDelegate {
let myName = "Alec"
// Im getting ready to navigate to my FriendViewController... //
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? FriendViewController {
print("Navigating to FriendViewController...")
destination.delegate = self
print("Set MeViewController as the delegate for FriendViewController.")
}
}
/*
You need to implement your function definition here to CONFORM to the protocol. When my friend Liam is ready,
he will use a button to greet me! Liam needs to know my name, though. So I'll remind him by sending it to
him when he asks for it.
*/
func greetFriend() -> String {
print("I am a protocol method getting called from FriendViewController.")
return self.myName
}
}
/*
This is the secondary view controller that is reached by navigating from the MeViewController.
*/
class FriendViewController: UIViewController {
let myName = "Liam"
/*
We set our delegate property here to have reference to the MeViewController so we can ask it for the name to greet
when Liam needs it.
*/
var delegate: GreetFriendDelegate?
// Liam needs his friends name here! Hurry, ask MeViewController! //
@IBAction func greetFriendAction(_ sender: Any) {
// Liam is asking MeViewController who he should greet //
let myFriend = self.delegate?.greetFriend()
print("Hello, \(myFriend)! My name is \(self.myName)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment