【问题标题】:Swift protocol method usageSwift 协议方法使用
【发布时间】:2014-07-25 20:06:56
【问题描述】:

所以我开始学习 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

那么,问题出在哪里?

【问题讨论】:

    标签: ios methods protocols swift xcode6


    【解决方案1】:

    问题是

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

    【讨论】:

    • 那么“?”是什么意思?实际上是什么意思?
    • 这意味着它是PeopleStackViewDataSourceOptional,即与单独的PeopleStackViewDataSource 不同的类型。阅读官方指南以了解更多信息。
    • 那么如果我删除了'?',我的检查和返回的语法是什么样的?
    • 您可以只使用self.datasource.stackViewNumberOfItems(self),但datasource 永远不会是nil
    • 试试return self.datasource ? self.datasource!.stackViewNumberOfItems(self) : 0 注意额外的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多