类型'[String]'的值没有成员'lastObject'

时间:2016-03-10 07:08:32

标签: ios xcode swift

我有错误(shoppingList.lastObject)

    var shoppingList = ["bananas", "milk", "vanilla ice cream"]
    var itemCount = shoppingList.count
    print("There are \(itemCount) items.")
    for item in shoppingList
    {
        print("I need to buy \(item).")
    }
    print("The most important item on my list is definitely \(shoppingList.lastObject)")

它说lastObject不是成员。

3 个答案:

答案 0 :(得分:2)

它是last而不是lastObject

var shoppingList = ["bananas", "milk", "vanilla ice cream"]
var itemCount = shoppingList.count
print("There are \(itemCount) items.")
for item in shoppingList {
    print("I need to buy \(item).")
}
print("The most important item on my list is definitely \(shoppingList.last)")

注意:使用.first获取第一个元素。

答案 1 :(得分:0)

数组

 let shoppingList = ["bananas", "milk", "vanilla ice cream"]
 print("The most important item on my list is definitely \(shoppingList.last)")

NSArray

 let shoppingList = ["bananas", "milk", "vanilla ice cream"] as NSArray
 print("The most important item on my list is definitely \(shoppingList.lastObject)")

NSMutableArray

 let shoppingList = ["bananas", "milk", "vanilla ice cream"] as NSMutableArray
 print("The most important item on my list is definitely \(shoppingList.lastObject)")

答案 2 :(得分:0)

首先,我将使用一些直接从Playground裁剪的图像为您提供我的代码示例。

我将仅使用您的代码发布所有已检查的阶段。最后,我将发布错误以便更好地理解。

<强> 1。你的问题(假设)   Your Problem

<强> 2。解决方案 Working Solution

第3。一些额外的 Extras

<强> 4。更多额外内容 More Extras

<强> 5。现在你可以在某些情况下遇到的错误 Error

谢谢

希望这会有所帮助。