Skip to content

Instantly share code, notes, and snippets.

@wanderingmatt
Created October 27, 2019 04:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wanderingmatt/2bf8fd78bd5ae125050cfabf2b9542bb to your computer and use it in GitHub Desktop.
Save wanderingmatt/2bf8fd78bd5ae125050cfabf2b9542bb to your computer and use it in GitHub Desktop.
let colors: [String] = [
"Blue",
"Green",
"Orange",
"Purple",
"Red",
"Yellow"
]
func randomBackgroundColor() -> Color? {
if let color = colors.randomElement() {
return Color(color)
}
return nil
}
@kennymeyers
Copy link

func randomBackgroundColor() -> Color? {
    // the .randomElement method on any array
    // returns an optional 
    // so in this case it would be String? 
    // because the compiler knows, and you declared
    // that this array contains strings
    // So you need to unwrap it before...
    if let color = colors.randomElement() {
        // ...you use it here
        // as Color(named:) also returns an optional (Color?)
        // but doesn't take an optional as a parameter
        // it's defined as Color(named: string) not Color(named: string?) 
        // so you need to make sure you have an actual value to use it
    }

    // Since there's no way to guarantee at a compiler level that the array
    // will have a randomElement, we need to return nil since it's possible
    // the other code won't be touched
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment