繁体   English   中英

Swift协议方法用法

[英]Swift protocol method usage

所以我开始学习Swift,因为它看起来比ObjC更好。 但是我必须感到厌倦(现在它在凌晨2点37分),因为我无法看到为什么Xcode尖叫的问题我试图调用未定义的成员。 请参阅以下代码:

PeopleStackViewDataSource.swift

import Foundation
import UIKit

protocol PeopleStackViewDataSource {

    func stackViewNumberOfItems(stackView: PeopleStackView) -> Int
    func stackViewGetView(indexPath: NSIndexPath) -> UIView
}

PeopleStackView.swift

import Foundation
import UIKit

class PeopleStackView: UIView {

    var datasource: PeopleStackViewDataSource? {
    didSet {
        self.redraw()
    }
    }

    var scaleDownBy: Double = 0.1

    init(frame: CGRect) {
        super.init(frame: frame)

    }

    init(frame: CGRect, datasource: PeopleStackViewDataSource) {
        super.init(frame: frame);
        self.datasource = datasource;
    }

    func numberOfItems() -> Int {
        return self.datasource ? self.datasource.stackViewNumberOfItems(self) : 0
    }

    func redraw() {

    }


}

问题是这行return self.datasource ? self.datasource.stackViewNumberOfItems(self) : 0 return self.datasource ? self.datasource.stackViewNumberOfItems(self) : 0其中Xcode表示stackViewNumberOfItems(self)

PeopleStackViewDataSource? 没有名为'stackViewNumberOfItems的成员

那么,问题在哪里?

问题是

PeopleStackViewDataSource?' does not have a member named 'stackViewNumberOfItems

但是PeopleStackViewDataSource ? (请注意?

您需要打开可选的datasource

func numberOfItems() -> Int {
    if let ds = self.datasource {
        return ds.stackViewNumberOfItems(self)
    } else { return 0 }          
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM