Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda