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
왜?
덕분에, 작동! 클래스 프로토콜에 대해 몰랐습니다. 기록을 위해, 나의 프로토콜은 또한 Printable을 따르고 있었고 올바른 프로토콜은 클래스 프로토콜이되도록했습니다 protocol BoardType : class, Printable – Maiaux
맞습니다 - 클래스에 관한 문서에 대한 링크를 제공 했어야합니다. only protocols] (https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/Protocols.html#//apple_ref/doc/uid/TP40014097-CH25-XID_422). –