Extract a Substring Behind a Colon in Swift

// Input: "foo:bar"
// Expected Output: "bar"
//

// Option 1
//
let str = "foo:bar"
if let indexOfColon = str.firstIndex(of: ":") {
  let output = String(str.suffix(from: indexOfColon).dropFirst())
  print(output)
}

// Option 2 (Equivalent version of Option 1)
//
let str = "foo:bar"
if let indexOfColon = str.firstIndex(of: ":") {
  let output = String(str[indexOfColon...].dropFirst())
  print(output)
}

// Option 3 (Favorite approach)
//
let str = "foo:bar"
let words = str.split(separator: ":", maxSplits: 1)
let output = String(words.last!)
print(output)

// Option 4 (Concise version of Option 3) 
//
let str = "foo:bar"
let output = String(str.split(separator: ":", maxSplits: 1).last!)
print(output)

I came up with Option 1 at first. Option 2 is an equivalent version of Option 1. I don’t really like the idea of slicing a sub-string containing the colon then drop it. I think Option 3 is better. Option 4 is a concise version of Option 3.


Posted

in

by

Tags:

Comments

Leave a comment