swiftlang / swift-book

The Swift Programming Language book
Apache License 2.0
1.72k stars 159 forks source link

Immediately invoked closures should be updated to use do-expressions. #323

Closed 7ombie closed 2 months ago

7ombie commented 2 months ago

Location

https://docs.swift.org/swift-book/documentation/the-swift-programming-language/initialization#Setting-a-Default-Property-Value-with-a-Closure-or-Function

Description

This code example uses empty parens after the closing brace to immediately invoke the closure that defines boardColors:

struct Chessboard {
  let boardColors: [Bool] = {
    var temporaryBoard: [Bool] = []
    var isBlack = false
    for i in 1...8 {
      for j in 1...8 {
        temporaryBoard.append(isBlack)
        isBlack = !isBlack
      }
      isBlack = !isBlack
    }
    return temporaryBoard
  }()
  func squareIsBlackAt(row: Int, column: Int) -> Bool {
    return boardColors[(row * 8) + column]
  } 
}

I've been trying to replace this syntax with do { ... } for a few years, and was told this would be available in Swift 6.

Correction

If I understand correctly, this should be legal (and preferred) in Swift 6:

struct Chessboard {
  let boardColors: [Bool] = do {
    var temporaryBoard: [Bool] = []
    var isBlack = false
    for i in 1...8 {
      for j in 1...8 {
        temporaryBoard.append(isBlack)
        isBlack = !isBlack
      }
      isBlack = !isBlack
    }
    return temporaryBoard
  }
  func squareIsBlackAt(row: Int, column: Int) -> Bool {
    return boardColors[(row * 8) + column]
  } 
}
7ombie commented 2 months ago

Just had a chance to check out Swift 6 Language Mode, and do-blocks are not implemented. I must have misunderstood something. Sorry for the noise.