如何在Swift中声明typedef

时间:2014-06-06 08:31:11

标签: typedef swift ios8

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

2 个答案:

答案 0 :(得分:120)

使用关键字typealias代替typedef

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

答案 1 :(得分:12)

添加到上面的答案:

<强>&#34; typealias&#34;是使用的关键字是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")

    } 

要使用输入参数创建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 */