Skip to content

Instantly share code, notes, and snippets.

# bendodson/RandomColorWithSeed (Swift 3) Last active Apr 24, 2018

Generate a random color with a seed string using Swift 3
 import UIKit func randomColor(seed: String) -> UIColor { var total: Int = 0 for u in seed.unicodeScalars { total += Int(UInt32(u)) } srand48(total * 200) let r = CGFloat(drand48()) srand48(total) let g = CGFloat(drand48()) srand48(total / 200) let b = CGFloat(drand48()) return UIColor(red: r, green: g, blue: b, alpha: 1) } // Identical seeds will lead to identical colors randomColor(seed: "ben") randomColor(seed: "ben") // Similarly, seeds with the same character values will lead to identical colors randomColor(seed: "ben") randomColor(seed: "neb") // However, this works well enough for something like article titles randomColor(seed: "iPhone 7: Jet Black vs. Black") randomColor(seed: "Vesper, Adieu") randomColor(seed: "Bloomberg’s Report on Apple Watch 2") randomColor(seed: "Is Donald Trump Actually Trying to Win?") randomColor(seed: "Uber to Begin Testing Self-Driving Cars in Pittsburgh") randomColor(seed: "Apple and the Pistol Emoji") randomColor(seed: "Jack Off") randomColor(seed: "Headphone Jacks Are the New Floppy Drives") randomColor(seed: "Brief Thoughts and Observations Regarding Today’s WWDC 2016 Keynote") randomColor(seed: "App Store Subscription Uncertainty")

### LeoNatan commented Apr 24, 2018

 Why not use `String.hash` instead of sum of scalars? It will bring you more entropy and will solve your case for `ben` and `neb`.
to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.