maqszur
maqszur

Reputation: 86

Swift generic sequence observable ambiguity

I've got following code

protocol NamedOption {
    var optionTitle: String { get }
}

struct DebugOption: NamedOption {
    let optionTitle: String
    let debugViewControllerType = UIViewController.self
}


func testFunk<T: Sequence>(d: Observable<T>) where T.Element == NamedOption {

}

func bindFullResultsRx() {
    let dd: Observable<[DebugOption]> = self.dataModel.debugOptions // this is defined and properly assigned earlier
    testFunk(d: dd)
}

and at the line where I call testFunk Xcode gives me following error:

Expression type '()' is ambiguous without more context

I have no idea why this is happening :( So far I was able to make it working by changing constraints on testFunk into this:

func funk<T: NamedOption>(d: Observable<[T]>) {

}

which seems to me more restrictive then version at the top. Does any one knows how to make it working with T: Sequence ?

Xcode version is 9.4, Swift version is 4.1.

Upvotes: 3

Views: 94

Answers (2)

maqszur
maqszur

Reputation: 86

After some digging and help from work colleagues I was able to make it working by simply changing == into : so it looks like this

func testFunk<T: Sequence>(d: Observable<T>) where T.Element: NamedOption {

}

It's just a matter of swift syntax https://docs.swift.org/swift-book/ReferenceManual/GenericParametersAndArguments.html

conformance-requirement → type-identifier : protocol-composition-type

Upvotes: 1

Daniel T.
Daniel T.

Reputation: 33979

OO and generics don't play too well together. In order to do what you want, you have to manually cast up as in:

testFunk(d: dd.map { $0.map { $0 as NamedOption } })

Upvotes: 0

Related Questions