Home > Blockchain >  Segmentation Fault in Swift
Segmentation Fault in Swift

Time:03-21

I get the following error when running swift run inside of an executable Swift Package:

zsh: segmentation fault  swift run

I have been able to boil the code down to the following:

enum MyEnum {
    case FirstCase
    case SecondCase
    case Other
}

struct MyEnumCollection {
    private var enums: [MyEnum]
}

extension MyEnumCollection: RangeReplaceableCollection {
    public init() {
        self.enums = []
    }
}

extension MyEnumCollection: Collection {
    public var startIndex: Int {
        0
    }

    public var endIndex: Int {
        self.enums.count
    }

    public subscript(position: Int) -> MyEnum {
        return self.enums[position]
    }

    public func index(after i: Int) -> Int {
        return self.enums.index(after: i)
    }
}

var collection = MyEnumCollection()

collection.append(MyEnum.FirstCase)

The segmentation fault happens on the last line, at the append statement.

Can someone help me understand why this is happening and how I should fix this?

CodePudding user response:

Update

Thanks to a comment from @MartinR it turns out that a even better solution is to implement replaceSubrange(_:with:) from the RangeReplaceableCollection protocol instead of append

mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, MyEnum == C.Element {
    self.enums.replaceSubrange(subrange, with: newElements)
}

Old solution

You need to implement append() as well

public mutating func append(_ newElement: MyEnum) {
    enums.append(newElement)
}

There is a default implementation of this function but of course it has no knowledge about your internal data source enums so it is not usable.


Going forward you might also need to implement other functions that has a default implementation.

Another thing, personally I would use the properties of the Array class as well when conforming to the protocol.

public var startIndex: Int {
    return enums.startIndex
}

public var endIndex: Int {
    return self.enums.endIndex
}
  • Related