Articles, podcasts and news about Swift development, by John Sundell.

Extracting subsequences

Published on 29 Aug 2019

Swift’s standard library offers several different APIs for extracting a range of elements from any sequence. For example, we can use dropFirst and dropLast to remove the first or last element — or use prefix and suffix to extract a subsequence with a given amount of leading or trailing elements.

// Since the first argument passed to a command line
// tool is the execution path, we drop it to have the
// first element become the first user-passed argument:
let arguments = CommandLine.arguments.dropFirst()

// Calling 'prefix' or 'suffix' on a sequence lets us
// extract a subsequence containing up to a certain
// number of elements, without crashing if the sequence
// doesn't contain enough elements:
let intro = text.split(separator: " ").prefix(10)
let outro = text.split(separator: " ").suffix(10)

// The above operations are optimized to not cause
// unnecessary copying, so if we want to turn the
// results into a new array, we must do so explicitly:
let words = Array(intro)

Support Swift by Sundell by checking out this sponsor:

Genius Scan SDK

Genius Scan SDK: Add a powerful document scanner to any iOS app. Genius Scan’s SDK features advanced image processing that’s the result of over 10 years of research and development and can be fully customized and integrated into your app with just one line of code. Mention Swift by Sundell when requesting a free demo to get a 20% discount on your license for a whole year.