How to Join and Extend in Beta 6 #swiftlang

I talked about the Beta 6 differences to print earlier this week but the Swift standard library introduced other significant changes with this update. Here are a few to consider.

Join has become joinWithSeparator, which you call after a sequence, interposing a separator between the elements of a sequence. For example:

["a", "b", "c"].joinWithSeparator(" ") // "a b c"
print(Array([[1, 2], [1, 2], [1, 2]]
    // [1, 2, 0, 1, 2, 0, 1, 2]

The sequence must be composed of strings or items that are themselves of sequence type, so you can use this with arrays but not with, for example, ints.

If you used extend to add contents to arrays and other range-replaceable collections (and, oh yes, I did), update that code to use appendContentsOf().

var x = [1, 2, 3]
x.appendContentsOf([4, 5, 6])
x // [1, 2, 3, 4, 5, 6]

The renaming also affected splice, which has the new related name insertContentsOf(). Supply a sequence to insert and an index to add it at.

x.insertContentsOf([0, 0], at: 2)
x // [1, 2, 0, 0, 3, 4, 5, 6]

The stride function, a commonly used fave for me, now operates on a Strideable type, so instead of from-through/to-by, you:

print(Array(1.0.stride(through: 3.0, by: 0.5)))
    //[1.0, 1.5, 2.0, 2.5, 3.0]

None of these introduce completely new features the way print did, but they’re certainly worth noting especially since the Swift migrator seems to mess up the stride migration, where it took a lot of by-hand-tweaking to get things working right.

Comments are closed.