如何在Swift中声明typedef

esh*_*esh 70 typedef swift ios8

如果我需要Swift中的自定义类型,我可以typedef,我该怎么做?(类似于闭包语法typedef)

Ani*_*ese 127

使用关键字typealias代替typedef

typealias CustomType = String
var customString:CustomType = "Test String"
Run Code Online (Sandbox Code Playgroud)


小智 12

添加到上面的答案:

"typealias"是使用的关键字是swift,它的功能类似于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")

    } 
Run Code Online (Sandbox Code Playgroud)

要使用输入参数创建typedef,语法如下所示:

    /*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 */
Run Code Online (Sandbox Code Playgroud)