Home > Net >  Property redefinition extension Swift
Property redefinition extension Swift

Time:03-24

I have a project A in which I have defined a struct, that only exists in project A, as follows

public struct Foo: RawRepresentable {
    public typealias RawValue = String
    
    public var rawValue: RawValue
    
    public init?(rawValue: RawValue) {
        self.rawValue = rawValue
    }
    
    public static let bar = Foo(rawValue: "bar")
}

Now, when I create an extension in project A that redefines the bar property, this will generate an error, which is logical.

extension Foo {
    // Invalid redeclaration of 'bar'
    static let bar = Foo(rawValue: "foo")
}

My real question comes when I define a new project B, that depends on A. I declared the same extension there, but no compiler error was given. Why is that?

import A

extension Foo {
    // No error, but shouldn't it give me one?
    static let bar = Foo(rawValue: "foo")
}

CodePudding user response:

Well, there's two ways to look at this. One is that it's a bug, the other is that it isn't. :) The canonical report is probably the one at https://bugs.swift.org/browse/SR-3228 [WARNING: that URL may go bad when Apple moves over to GitHub Issues for its Swift bug reporting]. But read also the discussion of the underlying mechanism from Jordan Rose in the comments to https://bugs.swift.org/browse/SR-8010, where it seems that the real issue is how to maintain Objective-C compatibility.

So yes, Apple knows about this, and they know it would be nice to issue a warning about doing something iffy, but you are in fact allowed to create what amounts to a same-named but different method/property in a different module, so on your head be it if you do so.

  • Related