Swift: Type does not conform to 'ArrayLiteralConvertible' protocol

Keep getting error in my playground saying Set is not ArrayLiteralConvertible protocol


struct Set<T: Hashable> : ArrayLiteralConvertible {
    typealias Element = T
    private var contents: [Element: Bool]

    init() {
        self.contents = [Element: Bool]()
    }

    // easier initialization
    init<S: SequenceType where S.Generator.Element == Element>(_ sequence: S) {
        self.contents = [Element: Bool]()
        Swift.map(sequence) { self.contents[$0] = true }
    }

    // allow Set creation through simple assignment using ArrayLiteralConvertible protocol
    internal static func convertFromArrayLiteral(elements: Element...) -> Set {
        return Set(elements)
    }
}

      

+3


source to share


3 answers


ArrayLiteralConvertible

you need to implement a type initializer init(arrayLiteral: Element...)

. Something like this will reuse your initializer, which takes a sequence:

init(arrayLiteral: Element...) {
    self = Set(arrayLiteral)
}

      

If you're doing this in a playground hit opt-cmd-enter to see more details in the editor assistant than just getting an error at the source. It shows the details of all the protocol requirements that you meet.



By the way, if you declared content like this:

private var contents: [Element: Bool] = [:]

      

you don't need to initialize it in each of your initializers.

+4


source


Protocol

ArrayLiteralConvertible

requires an initializer init(arrayLiteral elements: Element...)

in the class

 init(arrayLiteral elements: Element...) {
     self = Set(elements)
 }

      

You don't need to use the function anymore convertFromArrayLiteral

. It was fast in the old version. It has been deprecated in the iOS 8.1 API. You just need the initializer above.



https://developer.apple.com/library/ios/releasenotes/General/iOS81APIDiffs/modules/Swift.html

http://swiftdoc.org/protocol/ArrayLiteralConvertible/

+1


source


Thank you, you are on the right track. I found the gist on github with some changes in the syntax of ArrayLiteralConvertible. He approached this melody:

init(arrayLiteral elements: T...) {
        self.init(elements)
}

      

This seems to work.

0


source







All Articles