Skip to content

UseExplicitNilCheckInConditions generates invalid rewrite #1066

@jmccance

Description

@jmccance

The new formatting rule for UseExplicitNilCheckInConditions generates invalid output when the righthand side returns a constrained generic type.

Reproduction

protocol P {}

struct S: P, Equatable { }

func getValue<T: P>(forKey: String) -> T? {
    nil
}

@main
struct UseExplicitNilCheckInConditionsBug {
  static func main() {
    /*
    // Before formatting
    if let _: S? = getValue(forKey: "fnord") {
        print("Found it")
    }
    */

    // ❌ error: type 'any (~Copyable & ~Escapable).Type' cannot conform to 'P' 
    //    note: only concrete types such as structs, enums and classes can conform to protocols
    if getValue(forKey: "fnord") != nil {
      print("Found it")
    }
  }
}

I think the correct rewrite would be:

    if getValue(forKey: "fnord") != (nil as S?) {
      print("Found it")
    }

Versions

swift --version:

swift-driver version: 1.127.14.1 Apple Swift version 6.2 (swiftlang-6.2.0.19.9 clang-1700.3.19.1)
Target: arm64-apple-macosx15.0

swift format --version:

6.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions