我的数组如何计数为 0?

How is my array count 0?

我有一个 UIPickerView。在我的代码解析 XML 请求之前,我设置了一个空白数组。因此,当我希望它用该数据填充数组时。以下是我如何设置所有内容。

var pickerData = []

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return pickerData.count
    }

    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return pickerData[row] as String
    }

func parser(parser: NSXMLParser!, foundCharacters string: String!) {
        if (seperatedSoap == "pickerDataString") {
            if (currentElementName == "name") {
                pickerData = [string]
                println(pickerData)
            }

        }

我显然没有把所有的代码都贴出来,但你应该能够理解这里发生了什么。现在我的控制台在解析后将其打印为我的 pickerData。

(
    "2x1 on recv-small"
)
(
    "2x1 on ship-small"
)
(
    "3x2 on avs-1"
)
(
    "2.25x2 on photo-large"
)
(
    "2.25x2 on recv-large"
)
(
    "2.25x2 on repair-large"
)
(
    "2x3 on wireless-1"
)
(
    "4x6 on ship-shiplbl"
)
(
    "4x6 on recv-shiplbl"
)
(
    "4x6 on wireless-shiplbl"
)

这正是我想要的,但它没有显示在我的 UIPickerView 中,因为它显然是空白的?我在这里做错了什么?

首先你应该使用

pickerData.append(string)

因为您的赋值总是将数组设置为包含单个(最后一个)元素。

那么您可能需要调用 reloadComponent

追加数组加法赋值运算符(+=):

pickerData += [string]

Swift Collection Types