如何在函数"增加"的任何实例的count属性中加1。被调用?
func increase() {
????.count += 1
}
答案 0 :(得分:0)
如果increase()
是计数对象的方法,请使用self
self.count += 1
或者,如果您希望它作为自由函数运行,则需要传入一个对象
func increase<T: Countable>(obj: T) {
countable.setCount(count: countable.getCount() + 1)
}
其中Countable是:
protocol Countable {
func getCount() -> Int
func setCount(count: Int)
}
示例实现
class SimpleCounter: Countable {
var count: Int = 0
func getCount() -> Int {
return count
}
func setCount(count: Int) {
self.count = count
}
}