如果我需要Swift中的自定义类型,我可以typedef
,我该怎么办? (类似于闭包语法typedef)
答案 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 */