If I require a custom type in Swift, that I could typedef
, how do I do it? (Something like a closure syntax typedef)
如果我需要一个Swift自定义类型,我可以用typedef,我该怎么做呢?(类似于闭包语法typedef)
2 个解决方案
#1
107
The keyword typealias
is used in place of typedef
关键字typealias被用来代替typedef
typealias CustomType = String
var customString:CustomType = "Test String"
#2
11
added to the answer above:
加上上面的答案:
"typealias" is the keyword used is swift which does similar function as typedef.
“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")
}
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 */
#1
107
The keyword typealias
is used in place of typedef
关键字typealias被用来代替typedef
typealias CustomType = String
var customString:CustomType = "Test String"
#2
11
added to the answer above:
加上上面的答案:
"typealias" is the keyword used is swift which does similar function as typedef.
“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")
}
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 */