2014-11-08 2 views
0

getter와 setter 모두에 "subscript"기능이있는 프로토콜 (정보 은닉 목적으로)을 정의하고 있습니다. 그런 다음이 프로토콜을 구현하는 클래스를 정의하고 있습니다.신속한 하위 스크립트 및 프로토콜

짧은 버전의 문제 : 클래스의 개체에 첨자를 사용하면 (예 : 좌변 자 및 setter 사용) 예상대로 모든 것이 작동합니다. 프로토콜 유형으로 선언 된 객체에서이 작업을 수행하면 "이 표현의 결과에 할당 할 수 없습니다"오류가 발생합니다.

긴 버전. 저는 Int의 이사회를 가지고 있습니다. 보드는 2D 매트릭스입니다. BoardType 프로토콜을 통해 게시판 유형을 공개합니다.

protocol BoardType { 
    var width: Int {get} 
    var height: Int {get} 
    subscript(x:Int, y:Int) -> Int {get set} 
} 

class Board : BoardType { 

    let width, height : Int 
    var matrix : Array2D<Int> 

    init(width: Int, height: Int) { 
     self.width = width 
     self.height = height 
     matrix = Array2D<Int>(cols: width, rows: height, defaultValue: 0) 
    } 

    subscript(x:Int, y:Int) -> Int { 
     get { 
      return matrix[x,y] 
     } 
     set { 
      matrix[x,y] = newValue 
     } 
    } 
} 

Array2D의 구현은 표준이다 : 나는 다음을 수행하는 경우, 그것을 작동합니다, 지금

class Array2D<T>{ 

    var cols:Int, rows:Int 
    var matrix:[T] 

    init(cols:Int, rows:Int, defaultValue:T){ 
     self.cols = cols 
     self.rows = rows 
     matrix = Array(count:cols*rows,repeatedValue:defaultValue) 
    } 

    subscript(x:Int, y:Int) -> T { 
     get{ 
      return matrix[cols * y + x] 
     } 
     set{ 
      matrix[cols * y + x] = newValue 
     } 
    } 

    func colCount() -> Int { 
     return self.cols 
    } 

    func rowCount() -> Int { 
     return self.rows 
    } 
} 

:

let board = Board(width: 4, height: 4) 
    board[1,1] = 10 

을 대신,이 프로토 타입을 사용하는 경우, 내가 얻을 오류

let board : BoardType = Board(width: 4, height: 4) 
    board[1,1] = 10 

왜?

답변

10

두 번째 컴파일러를 let으로 선언했기 때문에 컴파일러에서이 작업을 수행하고 있으며 이 값 유형이 될 수 있습니다.이 경우 첨자 setter는 변경 표현식입니다. 두 수정 - BoardType으로 선언 할 때 하나 var를 사용

var board : BoardType = Board(width: 4, height: 4) 
board[1,1] = 10 

또는 확인 BoardType 클래스 프로토콜 :

protocol BoardType: class { 
    var width: Int {get} 
    var height: Int {get} 
    subscript(x:Int, y:Int) -> Int {get set} 
} 
+0

덕분에, 작동! 클래스 프로토콜에 대해 몰랐습니다. 기록을 위해, 나의 프로토콜은 또한 Printable을 따르고 있었고 올바른 프로토콜은 클래스 프로토콜이되도록했습니다 protocol BoardType : class, Printable – Maiaux

+0

맞습니다 - 클래스에 관한 문서에 대한 링크를 제공 했어야합니다. only protocols] (https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_422). –

관련 문제