1

According to the documentation:

To add RangeReplaceableCollection conformance to your custom collection, add an empty initializer and the replaceSubrange(_:with:) method to your custom type.

But in practice it's not required! (except for empty initializer)

// Just stubs for minimal reproducible code
struct Category: Hashable {}
struct Product {}

struct ProductCollection {
    typealias DictionaryType = [Category : [Product]]

    // Underlying, private storage
    private var products = DictionaryType()

    // Enable our collection to be initialized with a dictionary
    init(products: DictionaryType = DictionaryType()) {
        self.products = products
    }
}

extension ProductCollection: Collection {
    // Required nested types, that tell Swift what our collection contains
    typealias Index = DictionaryType.Index
    typealias Element = DictionaryType.Element
    
    // The upper and lower bounds of the collection, used in iterations
    var startIndex: Index { return products.startIndex }
    var endIndex: Index { return products.endIndex }
    
    // Required subscript, based on a dictionary index
    subscript(index: Index) -> Iterator.Element {
        get { return products[index] }
    }
    // Method that returns the next index when iterating
    func index(after i: Index) -> Index {
        return products.index(after: i)
    }
}

extension ProductCollection: ExpressibleByDictionaryLiteral {
    init(dictionaryLiteral elements: (Category, [Product])...) {
        self.init(products: .init(uniqueKeysWithValues: elements))
    }
}

extension ProductCollection: RangeReplaceableCollection {
    init() {
        products = DictionaryType()
    }
    
//    func replaceSubrange<C: Collection, R: RangeExpression>(_ subrange: R, with newElements: C)
//        where Self.Element == C.Element, Self.Index == R.Bound {
//    }
}

The code is taken from a great (but not related to the post's topic) John Sundell article.
This code compiles even though replaceSubrange function is not provided.

One more question. Why should I provide an empty initializer explicitly in this situation? I can initialize the struct like ProductCollection() without having that initializer. I can do this for many reasons: 1) products property has initializing value provided 2) main initializer has default value provided 3) there is also a ExpressibleByDictionaryLiteral initializer which can be used to initialize an empty object.
So why I have to provide one more empty initializer explicitly?

But please, the first question about replaceSubrange function is more important :)

0

1 Answer 1

3

That is a bug which has also been discussed in the Swift forum:

The reason is that there is an overload of the replaceSubRange() method (taking a RangeExpression as the first argument) which the compiler erroneously accepts as satisfying the protocol requirement.

But note that even if the code compiles without implementing the required method, it does not work and leads to an infinite loop. Here is a short example:

struct MyCollection : MutableCollection {

    private var storage: [Int] = []

    init(_ elements: [Int]) { self.storage = elements }

    var startIndex : Int { return 0 }
    var endIndex : Int { return storage.count }

    func index(after i: Int) -> Int { return i + 1 }

    subscript(position : Int) -> Int {
        get { return storage[position] }
        set(newElement) { storage[position] = newElement }
    }
}

extension MyCollection: RangeReplaceableCollection {
    init() { }
}

var mc = MyCollection([0, 1, 2, 3, 4, 5])
mc.replaceSubrange(0..<3, with: [2, 3, 4])

Running that code leads to an “infinite” loop and eventually crashes with EXC_BAD_ACCESS due to a stack overflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.