swiftswift-extensions

How do I create an init method for a struct which is only visible in tests?


I want to create an init method for my struct with a bunch of default values for use in unit tests. I don't want the main module to be able to see this init method.

I thought I could simply create an extension of my struct in my test class's file, but this doesn't work:

Foo.swift (in app target):

public struct Foo {

    public let bar: Int

    public init(colour: String) {
        self.bar = colour == "Green" ? 0 : 1
    }

}

FooExtension.swift (in test target):

extension Foo {

    public init(bar: Int = 42) {
        self.bar = bar
    }

}

Note the non-default initializer in the main file, so the Swift compiler does not automatically create the memberwise initializer for me. Maybe this has something to do with the problem, maybe not.

The Swift compiler complains Cannot assign to 'bar' in 'self'. But when I copy that init method into the original definition of my Foo struct in my main target, it works fine. I get the same results with or without the default parameter values.

Is this a Swift compiler bug or something to do with defining extensions in one module for structs defined in another? Everything works fine when I try and replicate this in a Playground.

I am using Swift 1.2 with Xcode Version 6.4 (6E35b)


Solution

  • I've had a response to the radar I filed on this; what I'm asking for is now explicitly disallowed.