1

Swift 5, iOS 13

I got this code... which is awful.

var horizonalOpacity = [Bool](repeating: false, count: 24)

self.horizonalOpacity[0] = true
self.horizonalOpacity[1] = true
self.horizonalOpacity[2] = true
self.horizonalOpacity[3] = true
self.horizonalOpacity[4] = true
self.horizonalOpacity[5] = true
self.horizonalOpacity[6] = true
self.horizonalOpacity[7] = true
self.horizonalOpacity[8] = true
self.horizonalOpacity[9] = true
self.horizonalOpacity[10] = true
self.horizonalOpacity[11] = true

I can replace with this code, which is ok.

for loop in 0...11 {
   self.horizonalOpacity[loop] = true
}

But can I do better? Can I use map perhaps? or an array slice perhaps?

3
  • I don’t think you can get more concise than that for loop Commented Jun 12, 2020 at 18:01
  • I have deleted my answer because an identical solution has been given before: stackoverflow.com/a/61889091/1187415 Commented Jun 12, 2020 at 18:15
  • Ok, I voted for that one too :) Commented Jun 12, 2020 at 18:57

2 Answers 2

1

What about

var horizonalOpacity = [Bool](repeating: true, count: 12) + 
                       [Bool](repeating: false, count: 12)
Sign up to request clarification or add additional context in comments.

2 Comments

This is good, but the answer using replacingSubrange was better, but it disappeared :( before I could vote it up?
1

You can also try to use mapInPlace extension proposed here:

extension MutableCollection {
    mutating func mapInPlace(_ x: (inout Element) -> ()) {
        for i in indices {
            x(&self[i])
        }
    }
}

Then you'd just write:

horizonalOpacity.mapInPlace { $0 = true }

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.