Home > Back-end >  How can I extend append method for Array in optional in Swift?
How can I extend append method for Array in optional in Swift?

Time:08-04

I am working to make this code works for optional array, but Xcode complain about:

Cannot assign value of type '[Wrapped.Element]' to type 'Wrapped'

Not sure why should be an error?

extension Optional where Wrapped: RangeReplaceableCollection, Wrapped.Element: Equatable {

    mutating func customAppend(_ value: Wrapped.Element) {
        if (self != nil) {
            self?.append(value)
        }
        else {
            self = [value] // Cannot assign value of type '[Wrapped.Element]' to type 'Wrapped'
        }
    }
    
}

CodePudding user response:

This will compile:

extension Optional where Wrapped: RangeReplaceableCollection, Wrapped.Element: Equatable {
    mutating func customAppend(_ value: Wrapped.Element) {
        if (self != nil) {
            self?.append(value)
        }
        else {
            self = .init([value]) // <--- RangeReplaceableCollection.init(_ elements:)
        }
    }
    
}

This works because RangeReplaceableCollection declares this init:

init<S>(_ elements: S) where S : Sequence, Self.Element == S.Element

So that init is available to any conforming type, and gives the appropriate concrete type.

On the other hand, trying to do self = [value] doesn't work, because that's trying to set self to an Array. But since the extension is on RangeReplaceableCollection, you can't set self to an Array, because that's not its type.

CodePudding user response:

Here is the correct and simplified answer:

extension Optional where Wrapped: RangeReplaceableCollection {

    mutating func customAppend(_ value: Wrapped.Element) {
        if (self != nil) {
            self?.append(value)
        }
        else {
            self = Wrapped([value])
        }
    }
    
}
  • Related