Hello Guys , I hope you all are enjoying mobikul blogs.
In today’s blog we will write a small program about the use of typealias in swift.
Now the first thing is “What is typealias and how to use it in our programming?”. Your answer is written below.
Typealias – A type alias declaration introduces a named alias of an existing type into your program. Type alias declarations are declared using the keyword typealias and have the following form:
typealias name = existing type
eg. typealias myDataType = String
ok , lets start by understanding the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import UIKit class TypeAliasViewController: UIViewController { @IBOutlet weak var valueLabel: UILabel! typealias test = (Bool?) -> Void typealias stringType = String override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeValuePressed(_ sender: Any) { self.callvalueTrue { (value) in if value == true{ callvalueFalse(alias: { (value) in if value == false{ self.valueLabel.text = "false" } }, teststring: "TypeString") } } } func callvalueTrue(alias:test){ alias(true) } func callvalueFalse(alias:@escaping test,teststring:stringType){ self.valueLabel.text = teststring DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: { alias(false) }) } } |
Alright guys lets dive into the code and learn whats happening here.
typealias test = (Bool?) -> Void
Created a test named typealias of type (Bool?)->Void
typealias stringType = String
Created a stringType named typealias of type String
1 2 3 |
func callvalueTrue(alias:test){ alias(true) } |
The above function will take test type parameter and will call it.
1 2 3 4 5 6 |
func callvalueFalse(alias:@escaping test,teststring:stringType){ self.valueLabel.text = teststring DispatchQueue.main.asyncAfter(deadline: .now() + 3.0, execute: { alias(false) }) } |
The function callvalueFalse will take two parameters of type test and stringType and will call the test after 3 seconds.
the @escaping keyword represents that our closure will escape the function means first the function will complete and on its completion the closure will get executed.
now inside our button action we called the functions.
1 2 3 4 5 6 7 8 9 |
self.callvalueTrue { (value) in if value == true{ callvalueFalse(alias: { (value) in if value == false{ self.valueLabel.text = "false" } }, teststring: "TypeString") } } |
self.valueLabel.text = “false”
the false text is assigned to label after 3 seconds because the callvalueFalse functions closure will get executed after 3 seconds.
i.e why we declared escaping there.
Thats enough guys If you have any confusion please comment below.