Search code examples
getteruicolorswift3

open override var description: String not called in Swift 3


I'm now using Xcode 8 GM (Version 8.0 (8A218a)) with Swift 3, my repo is: https://github.com/yeahdongcn/UIColor-Hex-Swift/tree/Swift-3.0 after I converted the Swift 2 syntax to Swift 3, I set two breakpoints in the following getter then I ran the test, the first one is not called, but the 2nd debugDescription gets called.

open override var description: String {
    return self.hexString(true)
}

open override var debugDescription: String {
    return self.hexString(true)
}

I created a playground it works the same

//: Playground - noun: a place where people can play

import UIKit

extension UIColor {
    public func hexString(_ includeAlpha: Bool) -> String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        self.getRed(&r, green: &g, blue: &b, alpha: &a)

        if (includeAlpha) {
            return String(format: "#%02X%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255), Int(a * 255))
        } else {
            return String(format: "#%02X%02X%02X", Int(r * 255), Int(g * 255), Int(b * 255))
        }
    }

    open override var description: String {
        return self.hexString(true)
    }

    open override var debugDescription: String {
        return self.hexString(true)
    }
}

let color = UIColor.yellow
color.description
color.debugDescription

enter image description here


Solution

  • You cannot override a method in an extension. You would need to use a subclass. The compiler should be complaining.

    It might have worked in Swift 2.x, but that was not correct behavior.