Last active
May 9, 2024 22:41
-
-
Save EnesKaraosman/efb9c2d989e51d20253976c8fb1aa734 to your computer and use it in GitHub Desktop.
Generatin random color in SwiftUI & UIKit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Very clever. Thanks.
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()
?
@treyharris AFAIK no difference in particular
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generating random color in UIKit & SwiftUI