Safely supporting new versions of Swift

Alan
Alan
Mar 5 · 6 min read

The first way; In one big go

The second way; Using conditional compilation

let str = "str"#if swift(>=4.2.2)
let i = String.Index(utf16Offset: 1, in: str)
#else
let i = String.Index(encodedOffset: 1)
#endif
#if compiler(>=5.0)
let i = String.Index(utf16Offset: 1, in: str)
#else
let i = String.Index(encodedOffset: 1)
#endif
#if compiler(>=5.0)
let i = String.Index(utf16Offset: 1, in: str)
#else
let i = String.Index(encodedOffset: 0) // changed offset to zero
#endif

The third way; using multiple Swift versions at the same time

please excuse my terrible graphing skills
please excuse my terrible people skills
/* Module A compiled in 4.2 mode */
let index = "string".index(of: "n")
/* Module B compiled in 5.0 mode */
let index = "string".firstIndex(of: "n")
Module A compiling in 4.2 mode
Module B compiling in 5.0 mode

Alan

Written by

Alan

iOS Software Engineer at Uber ★

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade