如何在 Swift 中声明 typedef

如果我需要一个自定义类型在 Swift,我可以 typedef,我如何做到这一点?(类似闭包语法 typedef)

41737 次浏览

The keyword typealias is used in place of typedef:

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

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 */