调用数组循环

时间:2016-12-15 02:29:32

标签: ios arrays swift swift3

如何从代码外打印我的数组。

public func buttonNameSetAndColor(){
    let buttonNamesAndColor = [button1, button2, button3, button4, button5, button6, button7, button8, button9, button10]

    var counter = 0

    for i in 0...9 {
        var val = NamePicker()
        buttonNamesAndColor[i]?.setTitle(val, for: .normal)
        buttonNamesAndColor[i]?.sizeToFit()

        // array to find duplicates
        var buttonValues = ["", "", "", "", "", "", "", "", "", ""] // array for button names
        buttonValues.insert(val, at: counter)
        counter += 1
        print(buttonValues[counter])
    }
}

我的代码在我的buttonNamesAndColor数组中为我的按钮命名,当每个按钮被赋予一个数组时,它被插入到我的buttonValues数组中。我希望看到该数组在函数外打印出来。

我想打印整个数组只是为了看到1.我可以在函数外部调用它,然后2.看它存储所有正确的值。

2 个答案:

答案 0 :(得分:0)

正如您目前所拥有的那样,您无法从buttonNamesAndColor函数外部访问buttonNameSetAndColor数组。在buttonNameSetAndColor函数的末尾,该数组不再在范围内。

以下所有选项都允许您在buttonNameSetAndColor功能之外访问和打印数组。

我假设您的button1, button2, etc.UIButton,但如果它们是另一种类型,则以下内容会有效。

选项1:在类/结构上为数组创建实例属性。这里可以使用其他变体,这取决于您的需求。

class SomeClass {
    private var buttonNamesAndColor: [UIButton]

    // or

    private var _buttonNamesAndColor = [UIButton]()
    var buttonNamesAndColor: [UIButton] {
        return _buttonNamesAndColor
    }

    // or

    var buttonNamesAndColor: [UIButton]

    ...
}

选项2:buttonNameSetAndColor函数返回一个数组。

public func buttonNameSetAndColor() -> [UIButton] {
    ...
}

选项3:如果您的button个实例是值类型。将数组作为inout参数传递。传递给此函数的数组的任何突变都将持续超出函数的范围。

public func buttonNameSetAndColor(_ array: inout [Button]) {
    ...
}

将使用以下内容调用此选项:

var buttonNamesAndColor = [button1, button2, button3] // Note "var" instead of "let"
buttonNamesSetAndColor(&buttonNamesAndColor) // Note "&" symbol

选项4:如果button个实例是引用类型,那么您可以将数组传递到buttonNameSetAndColor函数中而不使用inout

public func buttonNameSetAndColor(_ array: [UIButton]) {
    ...
}

这将使用如下:

var buttonNamesAndColor = [button1, button2, button3] // Note "var" instead of "let"
buttonNamesSetAndColor(buttonNamesAndColor)

答案 1 :(得分:0)

public func buttonNameSetAndColor(){

    let buttonNamesAndColor = [button1, button2, button3, button4, button5, button6, button7, button8, button9, button10]

    var counter = 0
    var buttonValues = ["", "", "", "", "", "", "", "", "", ""] // array for button names

    for i in 0...9 {
        var val = NamePicker()
        buttonNamesAndColor[i]?.setTitle(val, for: .normal)
        buttonNamesAndColor[i]?.sizeToFit()

        // array to find duplicates
        buttonValues.insert(val, at: counter)
        counter += 1
        print(buttonValues[counter])
    }
}