How do I declare typedef in Swift

TypedefSwiftIos8

Typedef Problem Overview


If I require a custom type in Swift, that I could typedef, how do I do it? (Something like a closure syntax typedef)

Typedef Solutions


Solution 1 - Typedef

The keyword typealias is used in place of typedef:

typealias CustomType = String
var customString: CustomType = "Test String"

Solution 2 - Typedef

added to the answer above:

"typealias" is the keyword used is swift which does similar function as typedef.

    /*defines a block that has 
     no input param and with 
     void return and the type is given 
     the name voidInputVoidReturnBlock*/        
    typealias voidInputVoidReturnBlock = () -> Void
    
    var blockVariable :voidInputVoidReturnBlock = {

       println(" this is a block that has no input param and with void return")

    } 

To create a typedef with input param the syntax is as shown below :

    /*defines a block that has 
     input params NSString, NSError!
    and with void return and the type 
    is given the name completionBlockType*/ 
    typealias completionBlockType = (NSString, NSError!) ->Void

    var test:completionBlockType = {(string:NSString, error:NSError!) ->Void in
        println("\(string)")
    
    }
    test("helloooooooo test",nil);
    /*OUTPUTS "helloooooooo test" IN CONSOLE */

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneshView Question on Stackoverflow
Solution 1 - TypedefAnil VargheseView Answer on Stackoverflow
Solution 2 - TypedefsreejithkrView Answer on Stackoverflow