Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

153
Views
Segmentation Fault in Swift

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!