I have a quick "Monthdata" array that I want to add every second value to the months array.
var monthData = [] let months = ["Jul 12","Aug 12","Sep 12","Oct 12"] for month in months { self.monthData.append(month) }
So basically I create an array of monthData:
["Aug 12","Oct 12"]
Try using modulo operator (%)
var monthData = Array<String>() let months = ["Jul 12","Aug 12","Sep 12","Oct 12"] var i : Int = 1 for month in months{ if(i%2 == 0){ monthData.append(month) } i = i + 1 } println(monthData)
Output:
[August 12, October 12]
You can also use the swift array method filterto get a filtered array,
filter
monthData = months.filter{ (dataValue) in (find(months, dataValue)! % 2 != 0) }
Swift 3 ( @maxkonovalov)
let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] let step = 2 let filtered = array.enumerated().flatMap { $0.offset % step == 0 ? $0.element : nil } // filtered: ["0", "2", "4", "6", "8"]
.
, N- (swift 2.0):
let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] let n = 2 let filteredArray = array.enumerate().flatMap { $0.index % n == 0 ? $0.element : nil } // filteredArray = ["0", "2", "4", "6", "8"]
, Strides map:
map
let months = ["Jul 12","Aug 12","Sep 12","Oct 12"] let monthData = stride(from: 1, to: months.count, by: 2).map { (value:Int) -> String in return months[value] } print(monthData)
Source: https://habr.com/ru/post/1599013/More articles:Как получить все последние сообщения коммитов для Xcode Bot "Запустить Script" Триггер? - gitHow to use swift 2 performSelector family of API? - swift@Retryable does not retry at startup using integration tests In a Spring application to load - javaSed template does not produce expected result - sedAccess the "id" value from an example side menu from Iconic frames using AngularJS and - javascriptBroadcastReceiver fires several times (PROVIDERS_CHANGED_ACTION) - androidUsing JSON content using LINQ / C # - jsonHow do you export a file from iOS when using the cordova file plugin? - iosUse crawl library in Android Studio - androidMy Ng class is not working - angularjsAll Articles