Nasiba
Nasiba

Reputation: 331

Extract a portion of two-dimensional array in Swift

I am trying to learn how to deal with two dimensional arrays in Swift. Here is a two-dim array I am working on:

var Image = [[1,2,3],[4,5,6],[7,8,9]]

If I want to extract only first two rows and first columns (2x2), how would I do that with Swift's range operator (...). I tried the following:

let extractedImage = Image[0...1][0...1]

It did not work. It rather gave me first two rows and columns were printed fully. How can I deal with this problem without using for loop?

Upvotes: 1

Views: 2009

Answers (3)

J.Wang
J.Wang

Reputation: 1236

Or image[0...1].map { $0[0...1].flatMap { $0 } }. :)

Upvotes: 2

Eendje
Eendje

Reputation: 8883

I'm not sure if I understood your question entirely but here's a safer way of getting [[1, 2], [4, 5]]

var images = [[1,2,3],[4,5,6],[7,8,9]]
let result = images.prefix(2).map { Array($0.prefix(2)) }

print(result) // [[1, 2], [4, 5]]

Upvotes: -1

Kevin
Kevin

Reputation: 17566

Image[0...1] returns [[1,2,3],[4,5,6]].

The second [0...1] is applied to that same array [[1,2,3],[4,5,6]] which gets the first 2 objects which are still [1,2,3] and [4,5,6].

What you want to do is apply the range to each of the arrays which you can do using map.

let extractedImage = Image[0...1].map({ $0[0...1] })

Upvotes: 1

Related Questions