Skip to content

Instantly share code, notes, and snippets.

@EnesKaraosman
Last active May 9, 2024 22:41
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EnesKaraosman/efb9c2d989e51d20253976c8fb1aa734 to your computer and use it in GitHub Desktop.
Save EnesKaraosman/efb9c2d989e51d20253976c8fb1aa734 to your computer and use it in GitHub Desktop.
Generatin random color in SwiftUI & UIKit
#if canImport(UIKit)
import UIKit
extension UIColor {
static var random: UIColor {
return UIColor(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1)
)
}
}
#elseif canImport(SwiftUI)
import SwiftUI
extension Color {
static var random: Color {
return Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1)
)
}
}
#else
// all other platforms – use a custom color object
#endif
@EnesKaraosman
Copy link
Author

Generating random color in UIKit & SwiftUI

@williamallenmd
Copy link

Very clever. Thanks.

@treyharris
Copy link

In a Swift 5.5 Playground released by Apple (“Recognizing Gestures”), the extension for SwiftUI’s Color gives random() as a func:

extension Color {
    static func random() -> Color {
        return Color(red: Double.random(in: 0...1), green: Double.random(in: 0...1), blue: Double.random(in: 0...1))
    }
}

I wonder if there are any semantic differences in behavior, or if it’s purely the syntactic difference of whether you use Color.random or Color.random()?

@mohitnandwani
Copy link

@treyharris AFAIK no difference in particular

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