Swift: how to perform a task n-1 times where n is the length of an array? -
i came this:
for x in 1...(myarray.count - 1) { task() } which ugly. there better way?
you have little careful, if array empty, crash:
let a: [int] = [] let range = 0..<a.count-1 // fatal error: can't form range end < start strides don’t have problem (since strideable things must comparable) do:
for _ in stride(from: 0, to: a.count - 1, by: 1) { // execute if a.count > 2 print("blah") } alternatively, if guard it, can use dropfirst:
for _ in (a.isempty ? [] : dropfirst(a)) { print("blah") } i advise against trying make neater creating pseudo-for-loop runs 1 less count times. there’s reason there’s no foreach or repeat functions in swift. these kind of loops seem nice @ first there lots of bugs arise them (for example, return or continue don’t work way might expect, it’s considered bad practice use higher-order function external mutation – whereas regular for loop suggestion mutation/side-effects likely).
the neatest extension-type solution extend array safe drop-first:
extension array { // version of dropfirst returns empty array both // empty , single-element array func safedropfirst() -> arrayslice<t> { return self.isempty ? [] : dropfirst(self) } } _ in myarray.safedropfirst() { dothing() }
Comments
Post a Comment