Swift에서 typedef를 어떻게 선언합니까?


81

Swift에서 사용자 정의 유형이 필요한 경우 typedef어떻게해야합니까? (클로저 구문 typedef와 같은 것)


5
Apple은 Apple (~ different ~)이며 typedef는 typealias. 아직 Apple의 Swift 프로그래밍 언어 를 읽었 습니까?
Kreiri

이 문서는 다음에서 온라인으로 찾을 수도 있습니다. developer.apple.com/library/prerelease/ios/navigation (페이지에서 "Swift Programming Language"검색 만 중단 할 수있는 직접 링크를 포함하지
않음

4
@Kreiri Swift typealiastypedef그 기능이보다 훨씬 적고 typedef현대 프로그래밍에 필요한 사용 사례에 훨씬 더 집중 하기 때문에 호출되지 않습니다 . 이것은 C의 작은 어휘가 ... 창의적인 방법 으로 결합되도록 의도 된 것과는 달리 특정 요구에 초점을 맞춘 더 큰 어휘를 갖는 Swift의 일반적인 디자인 원칙을 따릅니다 . 애플이 그것을 부르기로 결정했다면 typedef사람들은 그것이 C처럼 작동 할 것이라고 기대할 것이다 typedef. 이것이 바로 Microsoft가 자주 직면하는 디자인 문제입니다. 기존 이름을 사용하지만 구현 방식이 다릅니다.
Slipp D. 톰슨

답변:


142

typealias대신 키워드 가 사용됩니다.typedef

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

이 클로저의 새로운 유형을 어떻게 만들 수 있습니까 letcompleteBlock : (NSString, NSError!)-> Void = {strg, error in myString = "Haider"println ( "My text : (myString)")}
Waqas Haider Sheikh

typealias newClosure = ((strg1 : NSString, num1 : NSNumber)-> Void)?
Waqas Haider Sheikh

@WaqasHaiderSheikh 당신은 좋아할 수 있습니다 typealias closureType = (NSString, NSError!) ->Void. 그리고 그것을 사용let completionBlock:closureType = {strg,error in //do something}
Anil Varghese 2014

15

위의 답변에 추가되었습니다.

"typealias"는 typedef와 유사한 기능을 수행하는 swift 키워드입니다.

    /*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 */
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.