Swift에서 제네릭을 사용하여 문제가 있습니다. Java의 제네릭 경험이 있으며 내가 사용함에 따라 지식을 번역하는 중입니다. . 그래서 같은 프로토콜에 정의 된 제네릭 매개 변수 형식을 취하는 방법이 있습니다제네릭을 사용할 때 'A'유형의 값을 예상되는 인수 유형 'A'로 변환 할 수 없습니다.
protocol Board {
func getPlace<T : Position>(position: T) -> Place
}
아이디어는 Board
가 SquareBoard
에 대한 XYPosition
같은 Position
의 자신의 유형을 가지고 있지만, 다른 종류의 수 있다는 것입니다 16 진수 보드의 위치.
/Users/Craig/projects/MyModule/Sources/SquareBoard.swift:16:39: error: cannot convert value of type 'XYPosition' to
expected argument type 'XYPosition'
let index = toIndex(position: position)
^~~~~~~~
as! XYPosition
내가 캐스팅 position
을 강제로하려고하면, 심지어 괴상 가져옵니다 :
/Users/Craig/projects/MyModule/Sources/SquareBoard.swift:16:48: warning: forced cast of 'XYPosition' to same type h
as no effect
let index = toIndex(position: position as! XYPosition)
^~~~~~~~~~~~~~
/Users/Craig/projects/MyModule/Sources/SquareBoard.swift:16:48: error: cannot convert value of type 'XYPosition' to
expected argument type 'XYPosition'
let index = toIndex(position: position as! XYPosition)
~~~~~~~~~^~~~~~~~~~~~~~
as! XYPosition
는 타입 A를 재정의
그러나, 아래 놀이터 조각은 아주 이상한 오류가 다른 신분으로 두 번째? 나는 내가 뭘 잘못하고 있는지 판단 할 수 없다. 아래 놀이터에서 문제를 재현 할 수 있습니다.
import Cocoa
protocol Position : Equatable {
}
struct XYPosition : Position {
let x : Int
let y : Int
}
func ==(lhs: XYPosition, rhs:XYPosition) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public class Test {
private func toIndex(position: XYPosition) -> Int {
return (position.y * 10) + position.x
}
func getPlace<XYPosition>(position: XYPosition) -> Int {
let index = toIndex(position: position as! XYPosition)
return 4
}
}