2016-10-20 2 views
0

Swift에서 제네릭을 사용하여 문제가 있습니다. Java의 제네릭 경험이 있으며 내가 사용함에 따라 지식을 번역하는 중입니다. . 그래서 같은 프로토콜에 정의 된 제네릭 매개 변수 형식을 취하는 방법이 있습니다제네릭을 사용할 때 'A'유형의 값을 예상되는 인수 유형 'A'로 변환 할 수 없습니다.

protocol Board { 
    func getPlace<T : Position>(position: T) -> Place 
} 

아이디어는 BoardSquareBoard에 대한 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 
    } 
} 

답변

1

실제 코드를 게시하지 않으므로 다소 혼란 스럽습니다. getPlace이 무슨 단서가 문제로하지 않는다하고 난 당신이

어느 쪽이든을 달성하기 위해 노력하고 정확하게 확실 해요, 당신의 놀이터 작업이, 희망 당신은 거기에서 작업 할 수 있습니다

protocol Position : Equatable { 
    var x: Int { get } 
    var y: Int { get } 
} 

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<T: Position>(position: T) -> Int { 
     return (position.y * 10) + position.x 
    } 

    func getPlace<T: Position>(position: T) -> Int { 
     let index = toIndex(position: position) 
     return index 
    } 
} 

먼저 원래 getPlace<XYPosition>에서 XYPosition은 로컬로 정의 된 유형이며 구조체와 관련이 없으므로 as! XYPosition을 호출하면 구조체가 아닌 로컬 형식으로 캐스팅하려고합니다.

둘째로, 구조체 사용 방법을 오해하고있는 것 같습니다. struct는 하위 클래스로 분류 될 수 없으므로 struct를 generic으로 사용할 수 없습니다. 프로토콜 또는 클래스 만. 구조체를 전달하는 경우에는 구조체 자체를 전달하면됩니다.

관련 문제