Steven Van Impe
Steven Van Impe

Reputation: 1173

Swift crashes (related to generics?)

What is wrong with this code? It crashes both the REPL and the compiler (segmentation fault 11) ... This is supposed to be a trivial generics example. The crashes seem due to the extension adding ArrayLiteralConvertible conformance, the base type List works fine on its own.

struct List<Item> {

    private var items: [Item] = []

    var count: Int {
        return items.count
    }

    func item(atIndex index: Int) -> Item? {
        if index < count {
            return items[index]
        } else {
            return nil
        }
    }

    mutating func add(item: Item) {
        items.append(item)
    }

    mutating func remove(atIndex index: Int) {
        if index < count {
            items.removeAtIndex(index)
        }
    }
}

extension List: ArrayLiteralConvertible {

    typealias Element = Item

    init(arrayLiteral elements: Item...) {
        items = elements
    }
}

var numbers: List<Int> = [1, 2, 3]

Upvotes: 1

Views: 61

Answers (1)

jtbandes
jtbandes

Reputation: 118741

This seems to be a bug, which has already been filed at https://bugs.swift.org/browse/SR-493

As a workaround, you can move the init(arrayLiteral:) and ArrayLiteralConvertible conformance into the main struct definition, which seems to avoid the crash.

Upvotes: 2

Related Questions