NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Swift Coding Challenges: Find longest prefix

Forums > Books

In the book Swift Coding Challenges, Chapter 12: Find longest prefix, the challenge is to "Write a function that accepts a string of words with a similar prefix, separated by spaces, and returns the longest substring that prefixes all words.

The book provided the following solution:

func challenge12(input: String) -> String {
    let parts = input.components(separatedBy: " ")
    guard let first = parts.first else { return "" }

    var currentPrefix = ""
    var bestPrefix = ""

    for letter in first {

        for word in parts {
            if !word.hasPrefix(currentPrefix) {
                return bestPrefix

        bestPrefix = currentPrefix

    return bestPrefix

I chose another approach. Could you offer critique on my approach compared with the given solution? Thanks !

func challenge12(input: String) -> String {

    var words = input.components(separatedBy: " ")
    words.sort(){$0.count < $1.count}
    var prefix = words[0]
    for i in 1..<words.count {
        prefix = prefix.commonPrefix(with: words[i])
        guard prefix.count > 0 else {return ""}
    return prefix
print(challenge12(input: "swift switch swill swim"))
print(challenge12(input: "flip flap flop"))
assert(challenge12(input: "swift switch swill swim") == "swi", "failed test")
assert(challenge12(input: "flip flap flop") == "fl", "failed test")


Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.