Swift 中有一些类似的方法。它们看起来很相似,实际上它们的功能也很相似。它们是:
popFirst()
, popLast()
, dropFirst()
, dropLast()
, removeFirst()
,removeLast()
特别是 popFirst()
和 removeFirst()
,根据 Apple doc :
func popFirst()
Removes and returns the first element of the collection.
func removeFirst()
Removes and returns the first element of the collection.
他们的文档描述完全一样。实际上我尝试了很多( Playground 上的整个页面)来查看这些方法之间是否存在一些显着差异。答案是一些方法之间存在一些非常小的差异,而一些方法完全相同根据我的测试。
一些方法,popFirst()
, popLast()
和dropLast()
, dropFirst()
是在 String 和 Array 上使用时不同。但根据我的测试,它们都可以用removeFirst()
和removeLast()
代替(尽管有一些细微的差别)。
所以我的问题是为什么 Swift 必须保留这些相似的方法。是不是有点多余?
最佳答案
虽然 Apple 没有让它很容易找到,但它确实提到 pop
为空集合返回 nil
,而 remove
抛出没有要删除的内容时出错。
但是,您应该能够从这些函数的签名中分辨出相同的内容:
popFirst
返回一个可选的,这意味着您甚至可以从空集合中弹出第一个元素
另一方面,removeFirst
不是可选的。像这样的签名意味着在无法返回值的状态下调用此方法是错误的。
这可以使用 playground 轻松确认:
var test1 = Set<String>(["a", "b"])
let x1 = test1.popFirst()
let y1 = test1.popFirst()
let z1 = test1.popFirst() // returns nil
var test2 = Set<String>(["a", "b"])
let x2 = test2.removeFirst()
let y2 = test2.removeFirst()
let z2 = test2.removeFirst() // Throws an error
关于swift - 为什么 Swift 需要这些类似的功能?这有点多余吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651995/