1

I was wandering..... Is possible to add some padding into an array? For example: if i have something like var array:[NSDate] = [] What kind of data can i put inside the array as padding to obtain an array of 5 elements like array[NSDate, padding, NSDate, padding , padding].

I would like to maintain the position and the index of the elements also if some of them are nil.

Hope I made myself clear.

Swalsz
  • 33
  • 2
  • You could make your array of [NSDate?] and then you can add nil to the array. You will have to optionally unwrap the values in the array though. – Will M. Feb 12 '16 at 21:17
  • If you're trying to maintain position in an array, maybe you should look into solving your problem with a dictionary? *[Int:NSDate]* – Dan Beaulieu Feb 12 '16 at 21:45
  • At the moment i solved using [AnyObject] and casting data if necessary, but i want to try using NSDictionary. Thanks you. – Swalsz Feb 12 '16 at 22:04

2 Answers2

0

Answering question for other users.

var array:[NSDate?] = [nil , nil, NSDate(), nil, nil]

[NSDate?] by Will M

var dictionary:[Int:NSDate?] = [0 : nil, 1 : nil, 2 : NSDate(), 3 : nil, 4 : nil]

[Int:NSDate?] by Dan Beaulieu

kayu li
  • 1
  • 2
0

The answer is yes you can. And if you need more than 5 you can automate the process easily. (You can plug this into a playground to test it.)

func addPaddingTo( var myArray:[AnyObject], intArray:[Int]) -> [AnyObject]{

    //we'll do some checking here to make sure the indices you are changing are in fact valid members of myArray.

    for number in intArray {

        if number < myArray.count {

            myArray[number] = "Padding"
        }
    }

    return myArray
}


var paddedArray = Array < AnyObject >( count: 5, repeatedValue: NSDate())

paddedArray = addPaddingTo(paddedArray, intArray:[1,3,4])
Mountain Man
  • 242
  • 2
  • 10