Swift协议方法用法

时间:2014-06-05 00:43:30

标签: ios methods protocols swift xcode6

所以我开始学习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,其中Xcode表示stackViewNumberOfItems(self)

  

PeopleStackViewDataSource?没有名为的成员   “stackViewNumberOfItems

那么问题出在哪里?

1 个答案:

答案 0 :(得分:3)

问题在于

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 }          
}