swift - Store first few elements in array in another array if they exist -
given array contains number of objects, how cleanly , safely first 3 elements out of store in new array? if array not contain @ least 3 elements, should not trigger runtime exception, instead should add number of elements in array new array.
i thought might work, won't compile in xcode 7, , if did don't imagine behave safely desire:
let arr1 = [1, 2, 3, 4, 5] let arr2 = arr1[0..<3] //expected: arr == [1, 2, 3] let arr1 = [1, 2] let arr2 = arr1[0..<3] //expected: arr2 == [1, 2] let arr1 = [int]() let arr2 = arr1[0..<3] //expected: arr2 == []
of course 1 this, or use loop, neither clean , concise. want find swiftier way.
let arr1 = [1, 2] var arr2 = [int]() if photos.count > 0 { arr2.append(arr1[0]) } if photos.count > 1 { arr2.append(arr1[1]) } if photos.count > 2 { arr2.append(arr1[2]) }
i think simplest way be
let arr2 = arr1.prefix(3)
Comments
Post a Comment