【问题标题】:Passing a class's properties to class method selectively in Swift在 Swift 中选择性地将类的属性传递给类方法
【发布时间】:2017-08-20 00:25:36
【问题描述】:
struct Bar
{
    var one:[Int] = []
    var two:[Int] = []
    var tri:[Int] = []
}

class foo
{
    var bar = Bar()

    func setupBar()
    {
        bar.one = [1]
        bar.two = [2,2]
        bar.tri = [3,3,3]
    }

    //bars are updated here
    func updateBars()
    {
        updateBar(bar.one, bar.two) //...here...
        updateBar(bar.two, bar.tri) //...here...
        //etc...
    }

    //Bar1 should be concatenated with Bar2, and thus Bar1 will be updated.
    func updateBar(_bar1:[Int], _bar2:[Int]) //...here...
    {

    }

在上面的例子中,updateBar方法的参数在定义和调用中的正确语法是什么?

我尝试使用 inout,但也没有用。

【问题讨论】:

    标签: swift class methods parameters


    【解决方案1】:

    您正在使用inout 的正确轨道,只是不要忘记在调用时有一个&

    所以,像这样声明函数:

    func updateBar(_ bar1: inout [Int], _ bar2:[Int])
    

    然后这样调用:

    updateBar(&bar.one, bar.two)
    

    我也放了一些代码:

    struct Bar
    {
        var one:[Int] = []
        var two:[Int] = []
        var tri:[Int] = []
    }
    
    class foo
    {
        var bar = Bar()
    
        func setupBar()
        {
            bar.one = [1]
            bar.two = [2,2]
            bar.tri = [3,3,3]
        }
    
        //bars are updated here
        func updateBars()
        {
            updateBar(&bar.one, bar.two) //...here...
            updateBar(&bar.two, bar.tri) //...here...
        }
    
        //Bar1 should be concatenated with Bar2, and thus Bar1 will be updated.
        func updateBar(_ bar1: inout [Int], _ bar2:[Int]) //...here...
        {
            bar1.append(contentsOf: bar2)
        }
    }
    
    let f = foo()
    f.setupBar()
    f.updateBars()
    

    【讨论】:

    • 如果你在回答中解释了你所做的事情,你会得到我的支持。
    • @JeremyP,你是对的。最好有一个解释,而不仅仅是简单的代码。 :)
    【解决方案2】:

    函数参数有一个参数标签和一个参数名称。如果不指定参数标签,调用函数必须使用参数名称来指定参数。所以如果你定义

    func updateBar(bar1:[Int], bar2:[Int]){}
    

    你必须像这样调用你的函数:

    updateBar(bar1: bar.one, bar2: bar.two)
    # in your case you should have called updateBar(_bar1: bar.one, _bar2: bar.two)
    

    如果你想在调用函数中省略参数标签,你应该使用_明确地将其标记为省略:

    func updateBar(_ bar1: [Int], _ bar2: [Int]){}  # note space between _ and bar1
    

    现在您可以在没有参数标签的情况下调用您的函数:

    updateBar(bar.one, bar.two)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-23
      • 2021-01-05
      • 2011-10-16
      • 2021-11-30
      • 1970-01-01
      • 2021-02-05
      • 2018-03-23
      相关资源
      最近更新 更多