Skip to content

Instance Method

choose(_:from:display:)

Prompts the user to choose an item from the supplied array. The chosen item will be returned.
func choose<T>(_ prompt: ConsoleText, from array: [T], display: (T) -> ConsoleText) -> T

Parameters

prompt

ConsoleText prompt to display to the user before listing options.

array

Array of CustomStringConvertible items to choose from.

display

A closure for converting each element of array to a ConsoleText for display.

Return Value

Element from array that the user chose.

Discussion

let color = console.choose("Favorite color?", from: ["Pink", "Blue"])
console.output("You chose: " + color.consoleText())

The above code will output:

Favorite color?
1: Pink
2: Blue
>

Upon answering, the prompt and options will be cleared from the console and only the output will remain:

You chose: Blue

See choose(_:from:) which uses CustomStringConvertible to display each element.