如何在Swift中声明typedef


78

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


5
苹果是Apple(〜不同〜),它们的typedef称为typealias。您阅读过Apple的Swift编程语言吗?
Kreiri

您也可以在以下位置在线找到此文档:developer.apple.com/library/prerelease/ios/navigation(而不是直接在页面上搜索“ Swift编程语言”而可能会中断的直接链接)
petert

4
@Kreiri Swifttypealias之所以没有被调用typedef是因为它的功能远小于的能力typedef,而更多地关注于现代编程所需的用例。这遵循了Swift的一般设计原则,即有一个较大的词典针对特定需求,这与C的小型词典要以创造性的方式组合在一起不同。如果苹果选择调用它typedef,人们会期望它像C一样工作typedef。这就是Microsoft经常遇到的设计问题-他们将使用既定名称,但其实现工作方式有所不同。
Slipp D. Thompson

Answers:


137

使用关键字typealias代替typedef

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

我怎样才能使这种关闭的一种新的类型让completeBlock:(NSString,NSError!)-> Void = {strg,myString中的错误=“ Haider” println(“ My text:(myString)”)}
Waqas Haider Sheikh

typealias newClosure =((strg1:NSString,num1:NSNumber)->无效)?
Waqas Haider Sheikh 2014年

@WaqasHaiderSheikh您可以喜欢typealias closureType = (NSString, NSError!) ->Void。并将其用作let completionBlock:closureType = {strg,error in //do something}
Anil Varghese 2014年

14

添加到上面的答案:

“ typealias”是使用的关键字,它具有与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 */
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.