Array – Recourse in SWIFT

In Python, I can create a repeating list like this:

>>> [1,2,3 ]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Is there a concise method in Swift?

The best thing I can do is:

1> var r = [Int]()
r: [Int] = 0 values
2> for i in 1...3 {
3. r += [1,2,3]
4. }
5> print(r )
[1, 2, 3, 1, 2, 3, 1, 2, 3]

You can create a 2D array and use flatMap to convert it to a one-dimensional array:

let array = [Int](repeating: [1 ,2,3], count: 3).flatMap{$0}

This is an extension that adds an init method and a repeat method, which uses an array that makes it cleaner:< /p>

extension Array {
init(repeating: [Element], count: Int) {
self.init([[Element]](repeating: repeating , count: count).flatMap{$0})
}

func repeated(count: Int) -> [Element] {
return [Element](repeating: self, count: count)
}
}

let array = [1,2,3].repeated(count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]

Please note that using the new initializer, if you use it without providing the expected type, you can get ambiguous method calls:

let array = Array(repeating: [1,2,3], count: 3) // Error: Ambiguous use of ‛init(repeating:co unt:)‛

Use instead:

let array = [Int](repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]

or

let array:[Int ] = Array(repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]

If you change Change the method signature to init(repeatingContentsOf: [Element], count: Int) or similar methods to avoid this ambiguity.

In Python, I can create one Such a repeating list:

>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3 , 1, 2, 3]

Is there a concise method in Swift?

The best thing I can do is:

1> var r = [Int]()
r: [Int] = 0 values
2> for i in 1...3 {
3. r += [1,2,3]
4. }
5> print(r )
[1, 2, 3, 1, 2, 3, 1, 2, 3]

You can create a 2D array, and then Use flatMap to convert it to a one-dimensional array:

let array = [Int](repeating: [1,2,3], count: 3).flatMap {$0}

This is an extension that adds an init method and a repeat method, which uses an array that makes it cleaner:

extension Array {
init(repeating: [Element], count: Int) {
self.init([[Element]](repeating: repeating, count: count).flatMap{$0})< br /> }

func repeated(count: Int) -> [Element] {
return [Element](repeating: self, count: count)
}
}

let array = [1,2,3].repeated(count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]

Please note that using the new initializer, if you use it without providing the expected type​​, you can get ambiguous method calls:

< pre>let array = Array(repeating: [1,2,3], count: 3) // Error: Ambiguous use of ‛init(repeating:count:)‛

Use instead:

let array = [Int](repea ting: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1, 2, 3]

or

< p>

let array:[Int] = Array(repeating: [1,2,3], count: 3) // => [1, 2, 3, 1, 2, 3, 1 , 2, 3]

If you change the method signature to init(repeatingContentsOf: [Element], count: Int) or similar methods, you can avoid this ambiguity.

< p>

Leave a Comment

Your email address will not be published.