반응형
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)]
사용법 (@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
반응형
'programing' 카테고리의 다른 글
이중 피벗 퀵 정렬과 퀵 정렬의 차이점은 무엇입니까? (0) | 2021.01.15 |
---|---|
Python 3.x에서 2.x와 유사한 정렬 동작을 얻으려면 어떻게해야합니까? (0) | 2021.01.15 |
C # : 형식의 모든 공용 (가져 오기 및 설정 모두) 문자열 속성을 가져 오는 방법 (0) | 2021.01.14 |
python / matplotlib의 세로 레이블이있는 Barchart (0) | 2021.01.14 |
Perl이 설치되지 않은 시스템에서 실행될 수 있도록 Perl 스크립트를 컴파일하려면 어떻게해야합니까? (0) | 2021.01.14 |