objective-cswiftswift-extensionsbridging

UIColor swift extension w/ class access from Objective-C


How can I access my darkGray color from objective-c please?

@objc
extension UIColor
{
    @objc
    public class Scheme1: NSObject {
        static var darkGray: UIColor! {
            return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
        }
    }
}

Solution

  • Assuming you're using Swift 4's @objc inference, darkGray must be declared @objc:

    @objc
    extension UIColor
    {
        @objc
        public class Scheme1: NSObject {
            @objc static var darkGray: UIColor! {
                return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
            }
        }
    }
    

    You can access darkGray from Objective-C using Scheme1.darkGray. Objective-C does not support nested classes, so Scheme1 is exported at the top level.


    If you really want to access Scheme1 in a namespaced manner even from Objective-C, you can make darkGray an instance property and store an instance of Scheme1 in your extension:

    @objc
    extension UIColor
    {
        @objc
        public class Scheme1: NSObject {
            @objc var darkGray: UIColor! {
                return UIColor(red: 16.0/255.0, green: 16.0/255.0, blue: 19.0/255.0, alpha: 1.0)
            }
        }
    
        @objc public static var scheme1 = Scheme1()
    }
    

    You can access darkGray using UIColor.scheme1.darkGray.