In Swift, what's the cleanest way to get the last two items in an Array?

前端 未结 9 1233
走了就别回头了
走了就别回头了 2020-12-09 07:52

Is there a cleaner way to get the last two items of an array in Swift? In general, I try to avoid this approach since it\'s so easy to be off-by-one with the indexes. (Using

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 08:13

    in swift 5 you can use suffix for get objects from the last and use prefix for get objects from the first, here is an example:

    let exampleArray = ["first text", "second text", "third text"]
    
    let arr1 = exampleArray.suffix(2) // ["second text", "third text"]
    let arr2 = exampleArray.prefix(2) // ["first text", "second text"]
    

    The result is a slice, but you can coerce it to an Array if you need to.

提交回复
热议问题