programing

Swift의 일반 유형 별칭

randomtip 2021. 1. 15. 08:06
반응형

Swift의 일반 유형 별칭


haskell에서는 다음과 같이 할 수 있습니다.

type Parser a = String -> [(a, String)]

Swift에서 비슷한 것을 만들려고했습니다. 지금까지 나는 운없이이 코드를 작성했습니다.

typealias Parser<A> = String -> [(A, String)]
typealias Parser a = String -> [(a, String)]
typealias Parser = String -> [(A, String)]

그래서 이것은 단순히 신속하게 불가능합니까? 이 동작을 구현하는 다른 방법이 있다면?

업데이트 : 이제 swift 3 https://github.com/apple/swift/blob/master/CHANGELOG.md 에서 일반 typealiases가 지원되는 것 같습니다 .


Generic typealias은 Swift 3.0부터 사용할 수 있습니다. 이것은 당신을 위해 작동합니다.

typealias Parser<A> = (String) -> [(A, String)]

다음은 전체 설명서입니다. https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/swift/grammar/typealias-declaration

사용법 (@Calin Drule 주석에서) :

func parse<A>(stringToParse: String, parser: Parser) 

typealias현재 제네릭과 함께 사용할 수 없습니다. 가장 좋은 방법은 파서 함수를 구조체 안에 래핑하는 것입니다.

struct Parser<A> {
    let f: String -> [(A, String)]
}

그런 다음 파서를 만들 때 후행 클로저 구문을 사용할 수 있습니다.

let parser = Parser<Character> { string in return [head(string), tail(string)] }

일반 유형 별칭 -SE-0048

상태 : 구현 됨 (Swift 3)

해결책은 간단합니다. 유형 별칭이 정의 범위 내에있는 유형 매개 변수를 도입하도록 허용합니다. 이를 통해 다음과 같은 것을 표현할 수 있습니다.

typealias StringDictionary<T> = Dictionary<String, T>
typealias IntFunction<T> = (T) -> Int
typealias MatchingTriple<T> = (T, T, T)
alias BackwardTriple<T1, T2, T3> = (T3, T2, T1)

여기 에서는 프로토콜 정의에서 typealias 를 사용하는 방법을 보여주는 typealias에 대한 예제를 제공 합니다. 이것이 typealias 를 이해하는 데 도움이되기를 바랍니다.

protocol NumaricType {
    typealias elementType
    func plus(lhs : elementType, _ rhs : elementType) -> elementType
    func minus(lhs : elementType, _ rhs : elementType) -> elementType
}

struct Arthamatic :NumaricType {

    func addMethod(element1 :Int, element2 :Int) -> Int {
       return plus(element1, element2)
    }
    func minusMethod(ele1 :Int, ele2 :Int) -> Int {
        return minus(ele1, ele2)
    }

    typealias elementType = Int

    func plus(lhs: elementType,  _ rhs: elementType) -> elementType {
        return lhs + rhs
    }
    func minus(lhs: elementType, _ rhs: elementType) -> elementType {
        return lhs - rhs
    }
}

산출:

let obj =  Arthamatic().addMethod(34, element2: 45) // 79

참조 URL : https://stackoverflow.com/questions/27084586/generic-typealias-in-swift

반응형