removeLast()
方法会从数组中移除最后一个元素。
示例
var brands = ["Dell", "Apple", "Razer"]
// removes and returns last element from brands
print(brands.removeLast())
// Output: Razer
removeLast() 语法
数组 removeLast()
方法的语法是
array.removelast(i: Int)
其中,array 是 Array
类的一个对象。
removeLast() 参数
removeLast()
方法可以接受一个参数
- i (可选) - 要从 array 末尾移除的元素数量
removeLast() 返回值
- 从 array 返回被移除的元素
示例 1:Swift 数组 removeLast()
var country = ["Nepal", "Greece", "Spain"]
// removes and returns last element from country
print(country.removeLast())
// print the modified array
print(country)
输出
Spain ["Nepal", "Greece"]
在这里,我们使用 removeLast()
方法从 country 数组中移除最后一个元素。
移除最后一个元素后,我们打印了修改后的数组。
示例 2:移除多个元素
var languages = ["Swift", "Python", "Java"]
print("Before removeLast():", languages)
// removes last two elements from languages
languages.removeLast(2)
print("After removeLast():", languages)
输出
Before removeLast(): ["Swift", "Python", "Java"] After removeLast(): ["Swift"]
在这里,languages.removeLast(2)
从 languages 中移除了最后的 2 个元素。