Advertisement
Don_Mag

Simple Closure example

Jul 20th, 2021
1,546
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.51 KB | None | 0 0
  1. // Start a new project
  2. //  Add a UILabel and UIButton to the default view controller
  3. //  connect the label to countLabel @IBOutlet
  4. //  connect the button to doFetch @IBAction
  5. //
  6. // each tap of the button will call fetch() in LoginManager.shared
  7. //  and use a 1-second delay to simulate fetching data from an API
  8.  
  9. class ViewController: UIViewController {
  10.    
  11.     @IBOutlet var countLabel: UILabel!
  12.    
  13.     override func viewDidLoad() {
  14.         super.viewDidLoad()
  15.        
  16.         // set the "callback" closure in LoginManager
  17.         LoginManager.shared.callback = { [weak self] str in
  18.             // safely unwrap self
  19.             guard let self = self else { return }
  20.             // we have to update UI elements on the main thread
  21.             DispatchQueue.main.async {
  22.                 // set the returned str to countLabel's text
  23.                 self.countLabel.text = str
  24.             }
  25.         }
  26.     }
  27.     @IBAction func doFetch(_ sender: Any) {
  28.         countLabel.text = "Calling API..."
  29.         LoginManager.shared.fetch()
  30.     }
  31.    
  32. }
  33.  
  34. class LoginManager {
  35.    
  36.     static let shared = LoginManager()
  37.    
  38.     // counter var
  39.     var myCounter: Int = 0
  40.    
  41.     // closure for communication
  42.     var callback: ((String) -> ())?
  43.    
  44.     func fetch() -> Void {
  45.         // increment the counter
  46.         myCounter += 1
  47.         // 1-second delay to simulate getting data from API
  48.         DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1, execute: {
  49.             // get a random number from 1 to 9999
  50.             let n = Int.random(in: 1...9999)
  51.             // use the closure to send it back as a string
  52.             self.callback?("API Count: \(self.myCounter) Random: \(n)")
  53.         })
  54.     }
  55.    
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement