Contextual Where Clause 'cannot be attached to a non-generic declaration'

According to the Swift Programming Language Guide 5.3, one can use Contextual Where Clauses.

This example, copied from the guide into a Playground should compile:

import Foundation

public protocol Container {
    associatedtype Item

extension Container {
    func average() -> Double where Item == Int  {
        var sum = 0.0
        for index in 0..<count {
            sum += Double(self[index])
        return sum / Double(count)

It does not. Xcode shows an error:

'where' clause cannot be attached to a non-generic declaration

What is necessary to run the above code successfully?

Put where at the extension:

extension Container where ... {

Yes, but putting at the extension is not a contextual where clause.

The Swift Guide explains that approach in the Contextual Where Clauses section.

Apparently the issue maybe due to mistakenly running 5.2.4. Checking that now...

Yeah, Iā€™m pretty sure it has been regarded as a bug. Not sure if/when it was fixed though.

It works for me on Xcode 11 beta 1. It's a new feature (SE-0267) so it's not going to work on Swift 5.2.4.

1 Like

Just tried on Xcode 12 beta 4. All works fine.

Sorry for the false alarm. I mistakenly thought I was running Swift 5.3 already.

1 Like