Thursday, February 25, 2021

How to check an element belongs to an array, in Swift

 There are multiple ways to achieve this, some that just work, and some just beautiful.

Here are some examples that achieve the same thing, but some are doing it in style:

//ugliest

func search1(friend: String, friends: [String]) -> Bool {

    var found = false

    for aFriend in friends {

        if friend == aFriend {

            found = true

        }

    }

    return found

}


//uglier

func search2(friend: String, friends: [String]) -> Bool {

    for aFriend in friends {

        if friend == aFriend {

            return true

        }

    }

    return false

}


//ugly

func search3(friend: String, friends: [String]) -> Bool {

    return friends.filter { $0 == friend }.count > 0

}


//okay

func search4(friend: String, friends: [String]) -> Bool {

    return !friends.filter { $0 == friend }.isEmpty

}


//beautiful but maybe the most difficult to understand

func search5(friend: String, friends: [String]) -> Bool {

    return !friends.allSatisfy{ $0 != friend }

}

Some test code:

let friends = ["Susan", "John", "Jimmy", "Mary"]

let friend1 = "Mary"

let friend2 = "Max"


search1(friend: friend1, friends: friends)

search2(friend: friend1, friends: friends)

search3(friend: friend1, friends: friends)

search4(friend: friend1, friends: friends)

search5(friend: friend1, friends: friends)


search1(friend: friend2, friends: friends)

search2(friend: friend2, friends: friends)

search3(friend: friend2, friends: friends)

search4(friend: friend2, friends: friends)

search5(friend: friend2, friends: friends)


Inspired by Mihaela's post