我在包含应用和观看应用之间传递一系列字符串时遇到了问题,我之前发布了一个关于收到错误的问题String is not identical to AnyObject
- 'String' is not identical to 'AnyObject' error
当我发布这个问题时,我正在声明手表应用程序的数组:
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)
行上收到了错误。
我哪里错了?
答案 0 :(得分: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
}