gpt4 book ai didi

swift - 我可以将 `inout` 与协议(protocol)扩展一起使用吗?

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:57 24 4
gpt4 key购买 nike

我有一个协议(protocol)及其扩展,以及一个符合该协议(protocol)的类。

protocol WarAbilities {
var strength: Int { get set }
func attack(inout opponent: WarAbilities)
}

extension WarAbilities {
func attack(inout opponent: WarAbilities) {
opponent.strength -= 1
}
}

class Warrior: WarAbilities {
var strength: Int

init(strength: Int) {
self.strength = strength
}
}

现在如果我想让两个战士打架:

let thug1 = Warrior(strength: 10)
let thug2 = Warrior(strength: 30)

thug1.attack(&thug2)

我收到此错误消息:

error: cannot pass immutable value of type 'WarAbilities' as inout argument

添加 mutating 看起来很有希望:

protocol WarAbilities {
var strength: Int { get set }
mutating func attack(inout opponent: WarAbilities)
}

extension WarAbilities {
mutating func attack(inout opponent: WarAbilities) {
opponent.strength -= 1
}
}

但编译器也不高兴,我无法理解新错误消息的含义:

error: cannot pass immutable value as inout argument: implicit conversion from 'Warrior' to 'WarAbilities' requires a temporary

因为 Warrior 符合 WarAbilities,我认为其中一个会起作用——但看起来 Swift 没有这种……协方差?我什至不确定我在说什么。

我的错误是什么?

最佳答案

让它成为一个 class 协议(protocol)并摆脱(当时)不必要的 inout 东西:

protocol WarAbilities : class {
var strength: Int { get set }
func attack(opponent: WarAbilities)
}

extension WarAbilities {
func attack(opponent: WarAbilities) {
opponent.strength -= 1
}
}

class Warrior: WarAbilities {
var strength: Int

init(strength: Int) {
self.strength = strength
}
}

let thug1 = Warrior(strength: 10)
let thug2 = Warrior(strength: 30)

thug1.attack(thug2)

thug2.strength // 29

(事实上,我不太清楚为什么你在这里需要一个协议(protocol);因为 Warrior 是一个类,你可以将 WarAbilities 作为它的父类(super class)。)

关于swift - 我可以将 `inout` 与协议(protocol)扩展一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com