【问题标题】:How to access variable from other classes to perform calculation in a class?如何从其他类访问变量以在类中执行计算?
【发布时间】:2017-09-08 14:59:26
【问题描述】:

我正在与 2 个班级合作创建一个银行系统,以从我的帐户中添加和扣除金额。我有两个类,一个用于输入我的交易金额和类型,另一个用于处理数学,例如在交易完成后从我的帐户中添加和扣除金额。

class TransactionManager {
    var bal: Int
    init(bal: Int = 0) {
        bal = bal
    }

    func addCredit(entry: Transaction) -> (res: Bool, bal: Int) {
        return (true, balance)
    }

    func deductCredit(entry: Transaction) -> (res: Bool, balance: Int ){
        return (true, balance)
    }
}

而我的另一个类是用来输入交易的

class Transaction {
    let description: String
    let credits: Int

    init(credits: Int, description: String = "") {
        self.credits = credits
        self.description = description
    }
}

现在我尝试添加一些条目,例如

let transactionManager = TransactionManager(balance: 25000)
let transaction = Transaction(credits: 10000, description: "Withdraw")
let a = transactionManager(entry: transaction)

我想修改我的代码,这样当我调用这个 add 或 deduct 方法时,我需要使用我通过 Transaction 类进行的信用条目添加/减去总余额。

我如何访问交易类的贷方金额并使用它来执行在我的实际余额中添加金额或减去金额的数学运算?

【问题讨论】:

  • 您阅读上一个问题的答案了吗?也许你应该花一些时间阅读 Swift 的书。从变量访问属性是非常基本的。
  • 仅供参考 - line bal = bal` 甚至无法编译。你想要self.bal = bal

标签: swift class object methods swift3


【解决方案1】:

我想你想要这样的东西

func addCredit(entry: Transaction) -> (res: Bool, bal: Int) {
    self.bal += entry.credits
    return (true, self.bal)
}

func deductCredit(entry: Transaction) -> (res: Bool, balance: Int ){
    self.bal -= entry.credits
    return (true, self.bal)
}

【讨论】:

  • 为什么这些都不验证交易是否有效?如果您为所有结果硬编码true,那么返回值的res 部分有什么意义?
猜你喜欢
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多