How do you create an immutable array in Swift?

This has changed with Xcode 6 beta 3. While arrays used to be semi-mutable, as you describe, with their elements changeable but their length fixed, now immutable arrays share the same value semantics as Dictionaries:

From the Xcode 6 beta 3 release notes:

• Array in Swift has been completely redesigned to have full value semantics like Dictionary and String have always had in Swift. This resolves various mutability problems – now a ‘let’ array is completely immutable, and a ‘var’ array is completely mutable – composes properly with Dictionary and String, and solves other deeper problems. Value semantics may be surprising if you are used to NSArray or C arrays: a copy of the array now produces a full and independent copy of all of the elements using an efficient lazy copy implementation. This is a major change for Array, and there are still some performance issues to be addressed. Please
!see the Swift Programming Language for more information. (17192555)

The original information on arrays in the Swift book was updated on 7th July 2014 to reflect the beta 3 changes. (If you’re using iBooks on a Mac, as I was, you may need to delete and re-download it to pick up the 7th July update—I couldn’t get the thing to update automatically.)

Leave a Comment