0

I have two colour variables:

var blue = UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)
var red = UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)

I have declared these variables in my EntryViewController, however, I also need to use them in my other ViewControllers. I was wondering if it were possible to use the same variables in multiple ViewControllers? I already know about passing data with segues, but I was wondering if there were a way to maybe declare the colours in their own class and subclass my ViewControllers with this class. Thank you.

marco
  • 656
  • 2
  • 6
  • 22
  • Why assign `UIColor()`, if you're going to immediately overwrite it with `UIColor(red:0.08, green:0.49, blue:0.49, alpha:1.0)`? – Alexander Jul 09 '17 at 16:33
  • I thought I needed to make it like that to change it later in my code, I have updated the code with your suggestion. Thankyou – marco Jul 09 '17 at 16:45
  • Why would you change the colour blue? That's a pretty consistent colour. – Alexander Jul 09 '17 at 16:46

2 Answers2

2

One approach here is to create an extension on UIColor. You can then make them global to your module.

extension UIColor {
    static var myRed: UIColor {
        return UIColor(red:0.61, green:0.12, blue:0.20, alpha:1.0)
    }
    static var myBlue: UIColor {
        return UIColor(red: 0.08, green: 0.49, blue: 0.49, alpha:1.0)
    }
}
Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • Sorry, I am new to programming. Would you mind further explaining this to me? – marco Jul 09 '17 at 16:46
  • `UIColor` is immutable. You can use one shared instance instead of creating a new instance for every caller – Alexander Jul 09 '17 at 16:46
  • @M.I Please read the Swift language guide. Stack overflow isn't an alternative to learning the language. https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html – Alexander Jul 09 '17 at 16:47
  • I am familiar with the Swift language; my language pertains more to Xcode and its functionalities than the Swift language. – marco Jul 09 '17 at 16:51
  • @M.I Are you sure? Extensions, static members, computed properties, and enums are all pretty basic parts of Swift... – Alexander Jul 09 '17 at 17:25
1

You could make these global variables, but that's frowned upon because it pollutes the global name space. Instead, you can make these static members of a new type. A class or struct would work, but typically, an enum is used for this, just to ensure that no instances of the type can be made.

enum Colors {
    static let blue = UIColor(red: 0.08, green: 0.49, blue: 0.49)
    static let red = UIColor(red: 0.61, green: 0.12, blue: 0.20)
}
Alexander
  • 59,041
  • 12
  • 98
  • 151
  • I am sorry, would you mind further explaining this to me? In specifically where I would declare it and how I would call it in my other `ViewControllers`? – marco Jul 09 '17 at 16:48