[swift-users] A confusing protocol extension behaviour/bug

Marc Palmer marc at anyware.co.uk
Mon Jan 1 11:29:39 CST 2018


Hi,

I hope everybody had a great New Year celebration.

I was tracking down a weird bug in my Swift code today. A property defined in a class in order to conform to a protocol was not being seen. A protocol extension provided a default value of `nil` for this property, so I knew where it was coming from. Turned out, in my class I had defined the property with the correct name but incorrect type - I declared it as `String` instead of `String?`. 

I isolated this behaviour in a playground, shown below, and it is pretty weird behaviour.

The output is:

Something1 has id: nil
Something2 has id: nil
Something3 has id: Correct
-- Direct access--
Something1 - nil
Something2 - nil
Something2 with String(describing:) - Wrong but compiles, returns wrong value
Something3 - Correct

The playground code:

======================

protocol Trackable {
    static var analyticsID: String? { get }
}

extension Trackable {
    static var analyticsID: String? { return nil }
}

class Something1: Trackable {
}

class Something2: Trackable {
    static var analyticsID: String = "Wrong but compiles, returns wrong value"
}

class Something3: Trackable {
    static var analyticsID: String? = "Correct"
}

func getID<T: Trackable>(_ trackable: T.Type) {
    if let id = trackable.analyticsID {
        print("\(trackable) has id: \(id)")
    } else {
        print("\(trackable) has id: nil")
    }
}

getID(Something1.self)
getID(Something2.self)
getID(Something3.self)

print("-- Direct access--")
print("Something1 - \(Something1.self.analyticsID ?? "nil")")
print("Something2 A - \(Something2.self.analyticsID ?? "nil")")
print("Something2 with String(describing:) - \(String(describing: Something2.self.analyticsID))")
print("Something3 - \(Something3.self.analyticsID ?? "nil")”)
======================

Thanks in advance for any information about my misinterpretations or recommendations of what parts are actually undesirable so that I can raise the JIRAs.

Cheers

—
Marc Palmer
Montana Floss Co. Ltd.

Soundproof – Music Player for Practice 
http://getsoundproof.com





More information about the swift-users mailing list