Search code examples
arraysswiftbackgrounduicolor

Random uicolor from string array


I wish to pick change the background Color of my swift application by calling a random Color from a predetermined string array such as (red, green, pink).

so i have that array and i want the background color to be randomly selected as one of thoses colors.

using self.bg.background color resulted in xcode saying that a string could not be converted into a uicolor


Solution

  • Here's an example of one way to do this:

    import UIKit
    
    extension Array {
      func randomElement() -> Element {
        return self[Int(arc4random_uniform(UInt32(self.count)))]
      }
    }
    
    extension UIColor {
      enum ColorEnum: String {
        case red   // = "red"
        case green // = "green"
        case blue  // = "blue"
        case pink  // = "pink"
    
        func toColor() -> UIColor {
          switch self {
          case .red:
            return .redColor()
          case .green:
            return .greenColor()
          case .blue:
            return .blueColor()
          case .pink:
            return UIColor(hue: 1.0, saturation: 0.25, brightness: 1.0, alpha: 1.0)
          }
        }
      }
    
      static func fromString(name: String) -> UIColor? {
        return ColorEnum(rawValue: name)?.toColor()
      }
    }
    
    let colors = ["red", "green", "pink"] // stored as String
    UIColor.fromString(colors.randomElement())
    
    let enumColors: [UIColor.ColorEnum] = [.red, .green, .pink] // stored as enum
    enumColors.randomElement().toColor()