String Interpolation Updates
Swift 4.2 implements string interpolation by interpolating segments:
let language = "Swift"
let languageSegment = String(stringInterpolationSegment: language)
let space = " "
let spaceSegment = String(stringInterpolationSegment: space)
let version = 4.2
let versionSegment = String(stringInterpolationSegment: version)
let string = String(stringInterpolation: languageSegment, spaceSegment, versionSegment)
In this code, the compiler first wraps each literal segment and then interpolates one with init(stringInterpolationSegment:) . Then, it wraps all segments together with init(stringInterpolation:)
Swift 5 takes a completely different approach
// 1
var interpolation = DefaultStringInterpolation(
literalCapacity: 7,
interpolationCount: 1)
// 2
let language = "Swift"
interpolation.appendLiteral(language)
let space = " "
interpolation.appendLiteral(space)
let version = 5
interpolation.appendInterpolation(version)
// 3
let string = String(stringInterpolation: interpolation)
Here’s what this code does:
Define a DefaultStringInterpolation instance with a certain capacity and interpolation count.
Call appendLiteral(:) or appendInterpolation(:) to add literals and interpolated values to interpolation.
Produce the final interpolated string by calling init(stringInterpolation:)
credit: raywenderlich