1

我在包含应用程序和手表应用程序之间传递字符串数组时遇到问题,我之前发布了一个关于接收错误的问题String is not identical to AnyObject- “字符串”与“AnyObject”错误不同

当我发布该问题时,我正在声明手表应用程序的数组,如下所示:

var tempNames = [""]
var tempAmounts = [""]
var tempDates = [""]

现在我这样声明它们:

var tempNames = []
var tempAmounts = []
var tempDates = []

这解决了另一个错误,但是我现在在另一行收到错误。现在,当我尝试在 TableView 中显示字符串时,我得到了错误'AnyObject' is not convertible to 'String'。这是我的代码:

    for (index, tempName) in enumerate(tempNames) {
        let rowNames = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController

        rowNames.nameLabel.setText(tempName)
    }

    for (index, tempAmount) in enumerate(tempAmounts) {
        let rowAmounts = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController

        rowAmounts.amountLabel.setText(tempAmount)
    }

    for (index, tempDate) in enumerate(tempDates) {
        let rowDates = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController

        rowDates.dateLabel.setText(tempDate)
    }

我在线上得到错误rowNames.nameLabel.setText(tempName)

我哪里错了?

4

1 回答 1

0

在 Swift 中,数组总是包含显式类型的对象……与 Objective-C 不同,数组不能包含任意对象。因此,您需要声明您的数组将包含字符串。

var tempNames = [String]()
var tempAmounts = [String]()
var tempDates = [String]()

这并不总是很明显,因为在某些工作代码中您不会看到这一点。这是因为如果编译器可以从上下文中推断出您将字符串存储在数组中,那么您可以省略显式类型定义。例如:

var tempNames = ["Sarah", "Seraj", "Luther", "Aroha"]

关于上面的代码,您需要强制转换as? String

    for (index, tempName) in enumerate(tempNames) {
    let rowNames = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController
    rowNames.nameLabel.setText(tempName) as? String
}

for (index, tempAmount) in enumerate(tempAmounts) {
    let rowAmounts = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController
    rowAmounts.amountLabel.setText(tempAmount) as? String
}

for (index, tempDate) in enumerate(tempDates) {
    let rowDates = recentsTable.rowControllerAtIndex(index) as RecentsTableRowController
    rowDates.dateLabel.setText(tempDate) as? String
}
于 2015-01-14T23:26:05.917 回答