Created
April 10, 2020 12:01
-
-
Save mfdeveloper/3e1727776a3a57941f5c943ffee71428 to your computer and use it in GitHub Desktop.
Swift 5 extension to convert an array into two dimensions in format: [ [ ],[ ] ]. It is good for mount two collumns grid/list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| extension Array { | |
| /** | |
| Transform an array in another array with 2 (two) dimensions | |
| in format: `[ [ ],[ ] ]` | |
| # Example | |
| ```swift | |
| let newArray = [1, 2, 3, 4].mapTwoDimensions() | |
| print(newArray) | |
| // Shows: [[1, 2], [3, 4]] | |
| ``` | |
| */ | |
| func mapTwoDimensions() -> [[Element]] { | |
| var arrayResult: [[Element]] = [] | |
| var currentIndex = 0, nextIndex = 0 | |
| for (index, _) in self.enumerated() { | |
| if index < self.count - 1 { | |
| if nextIndex == 0 { | |
| nextIndex = currentIndex + 1 | |
| } else if nextIndex > 0 { | |
| currentIndex = nextIndex + 1 | |
| nextIndex = currentIndex + 1 | |
| } | |
| if nextIndex >= self.count { | |
| if(self.indices.contains(currentIndex)) { | |
| arrayResult.append([self[currentIndex]]) | |
| } | |
| continue | |
| } else { | |
| arrayResult.append([self[currentIndex], self[nextIndex]]) | |
| } | |
| } else if self.count == 1 { | |
| arrayResult.append([self[index]]) | |
| } | |
| } | |
| return arrayResult | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment