Swift - 访问函数

时间:2018-02-13 20:33:25

标签: swift

这里是新的和新的编码(或至少尝试!)。我有我想象的是一个非常简单的问题。我在这里查看答案Accessing variable outside function in Swift,但我不能将它与我自己的例子相协调(可能是因为我很抱歉对不起!)

无论如何....这是我的代码,它只是试图计算你用x金额购买x盒牛奶所能获得多少变化。这一切都在工作,但最后我想在函数中使用变量打印摘要(我想有一些重复/它有点无意义但我只是想学习你在理论上如何做到这一点!)

所以...代码......

//here i'm setting the function to calculate the total 
//price (they are £2 each) and the change I'm due

func getMilk(howManyMilkCartons : Int, howMuchMoneyPaid : Int) -> Int {
    print("go to the shops")
    print("buy \(howManyMilkCartons) milks")

    let priceToPay = howManyMilkCartons * 2

    print("pay £\(priceToPay)")
    print("come home")

    let change = howMuchMoneyPaid - priceToPay
    return change

}

// here i'm setting the variables which inform how many milks
//i'm buying and how much money i'm using

var amountOfChange = getMilk(howManyMilkCartons : 2, howMuchMoneyPaid : 10)

print ("hello, your change is £\(amountOfChange)")

所以,在底部,而不是我的印刷声明只有一点变化,我想做的是(仅用于学习)像

“你的改变是(改变的数量)从购买”X卡通牛奶“费用”£X“,并且你支付”X金额“(即使用函数内部的变量,在功能 - 如果可能的话)

我知道这是一个大量的菜鸟问题,在我引用的问题中可能会被正确覆盖,但我无法真正遵循这个例子,所以很抱歉,如果是这样的话!谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

howManyMilkCartonshowMuchMoneyPaid是通过将参数传递给函数而创建的局部变量。您无法在函数体外访问它们。但是,在您的情况下,您只需要声明具有函数外部范围的新的两个变量(或常量),您可以为其分配值,然后将它们用作参数:

// function is the same
func getMilk(howManyMilkCartons : Int, howMuchMoneyPaid : Int) -> Int {
    print("go to the shops")
    print("buy \(howManyMilkCartons) milks")

    let priceToPay = howManyMilkCartons * 2

    print("pay £\(priceToPay)")
    print("come home")

    let change = howMuchMoneyPaid - priceToPay
    return change

}

// declare your constants (or variables if you want) here:

let numberOfCartons = 2
let moneyPaid = 10

// use those constants as arguments to the function
var amountOfChange = getMilk(howManyMilkCartons : numberOfCartons, howMuchMoneyPaid : moneyPaid)

// and access them here as well
print ("hello, your change is £\(amountOfChange) after buying \(numberOfCartons) cartons of milk for \(moneyPaid) pounds")

答案 1 :(得分:0)

这是另一种看待这种情况的方式。如果您想要该功能之外的信息,则可能(在完整程序中)您希望将其作为购买的连贯记录。

所以,考虑一下......

class MilkPurchase {
    let cartons: Int
    let paid: Int

    var change = 0
    var price = 0

    init(cartonCount: Int, moneyPaid: Int) {
        cartons = cartonCount
        paid = moneyPaid
        price = cartonCount * 2
        change = paid - price
    }

}

func purchaseMilk(howManyMilkCartons : Int, howMuchMoneyPaid : Int) -> MilkPurchase {
    // Other logic perhaps
    return MilkPurchase(cartonCount: howManyMilkCartons, moneyPaid: howMuchMoneyPaid)
}

let purchaseRecord = purchaseMilk(howManyMilkCartons: 3, howMuchMoneyPaid: 10)
print(purchaseRecord.change)