Ask Your Question
0

How can I convert a Swift array into an array of tuples?

asked 2021-09-17 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-11 18:00:00 +0000

ladyg gravatar image

You can convert a Swift array into an array of tuples by using the map function. Here's an example:

let array = ["apple", "banana", "orange"]

let tupleArray = array.map { fruit -> (String, Int) in
    let count = fruit.count
    return (fruit, count)
}

print(tupleArray) // [("apple", 5), ("banana", 6), ("orange", 6)]

In this example, the map function is used to iterate over the array of String and map each element to a tuple containing the original element and its character count. The resulting tupleArray is of type [(String, Int)].

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-09-17 11:00:00 +0000

Seen: 10 times

Last updated: Mar 11 '23