如何使用私有集扩展协议?

时间:2017-05-22 14:34:24

标签: swift protocols private swift-protocols swift-extensions

我正在编写一个具有readOnly标签的协议。我想扩展它并给它一个默认的实现,其中符合类型是UITextView

代码:

protocol CountingView {

    var keyboardLabel : UILabel {get}   
}

extension CountingView where Self : UITextView {

    var keyboardLabel : UILabel {
        get {
            let label = UILabel()
            label.textColor = UIColor.white
            label.translatesAutoresizingMaskIntoConstraints = false

            return label
        }
        private (set) {
            keyboardLabel = newValue
        }
    }
}

但是,当我在private之前添加set时,我收到以下错误。

  

预期' get',' set',' willSet'或者' didSet'要启动的关键字   访问者定义

我查了解这个错误的其他问题,但没有发现它们与我的相关。

2 个答案:

答案 0 :(得分:5)

你只是把私人放在错误的地方:

private(set) var keyboardLabel : UILabel {
    get {
        let label = UILabel()
        label.textColor = UIColor.white
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }
    set {
        keyboardLabel = newValue
    }
}

答案 1 :(得分:0)

只需将您的计算属性import java.awt.image.BufferedImage; import java.io.IOException; public class ImagePreprocessor { private String filename; private int num_v_slices; private int num_h_slices; private int minSize; private int width, height; private int chunkWidth, chunkHeight; private int indexI, indexJ; String hdfs_address, local_directory; public ImagePreprocessor(String filename, int num_v_slices, int num_h_slices, int kernel_radius, int gradient_radius, String hdfs_address, String local_directory) throws IOException{ this.hdfs_address = hdfs_address; this.local_directory = local_directory; // all "validate" methods throw errors if input data is invalid checkValidFilename(filename); checkValidNumber(num_v_slices, "vertical strips"); this.num_v_slices = num_v_slices; checkValidNumber(num_h_slices, "horizontal strips"); this.num_h_slices = num_h_slices; checkValidNumber(kernel_radius, "kernel radius"); checkValidNumber(gradient_radius, "gradient radius"); this.minSize = 1 + 2 * (kernel_radius + gradient_radius); getImageData(); // loads image and saves width/height to class variables validateImageSize(); chunkWidth = validateWidth((int)Math.ceil(((double)width) / num_v_slices)); chunkHeight = validateHeight((int)Math.ceil(((double)height) / num_h_slices)); indexI = 0; indexJ = 0; } public boolean hasAnotherChunk() { return indexI < num_h_slices; } public int[] getChunkIndicesAndIndex() { int[] ret = new int[5]; ret[0] = indexI; ret[1] = indexJ; ret[2] = indexI*num_v_slices + indexJ; ret[3] = chunkWidth; ret[4] = chunkHeight; indexJ += 1; if (indexJ >= num_v_slices) { indexJ = 0; indexI += 1; } return ret; } } 设为:

private