Not a good idea to store the entire layout as a single String
. You should store each grid along with its solution as a separate item, say in a JSON file.
I mean, you can do it, using something like this:
import SwiftUI
extension String {
//breaks a String into smaller strings of the given length
//this would be even easier using the Swift Algorithms package
func chunked(by length: Int) -> [String] {
guard length < self.count else {
return [self]
}
var startIndex = self.startIndex
var results: [Substring] = []
while startIndex < self.endIndex {
let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
results.append(self[startIndex..<endIndex])
startIndex = endIndex
}
return results.map { String($0) }
}
}
struct Square: View {
let squareString: String
let solution: String = "" //???
//this would ideally be passed in
//but how is it determined?
let displaySolution: Bool
let cols: [GridItem] = Array(repeating: .init(.flexible(), spacing: 5), count: 3)
var body: some View {
LazyVGrid(columns: cols, spacing: 20) {
ForEach(Array(squareString), id: \.self) { character in
Text(String(character))
.foregroundColor(displaySolution && solution.contains(character) ? .green : .primary)
}
}
}
}
struct NumberSquares: View {
@State private var showSolution = false
let cols: [GridItem] = Array(repeating: .init(.flexible(), spacing: 40), count: 3)
let s = "987246351654173928321985746128634795537892461694157832519472863286319745473568219"
var body: some View {
VStack {
Toggle("Show Solution", isOn: $showSolution)
.padding(.vertical)
LazyVGrid(columns: cols, spacing: 40) {
ForEach(s.chunked(by: 9), id: \.self) { ss in
Square(squareString: ss, displaySolution: showSolution)
}
}
}
.font(.system(size: 21))
.padding()
}
}
struct NumberSquares_Previews: PreviewProvider {
static var previews: some View {
NumberSquares()
}
}
You can chunk the 81-number string into smaller, 9-number strings for display in a grid, but then how do you indicate which 3 numbers out of each 9-number grid is the solution? Ideally, you would pass in the solution when you create each Square
, but given, e.g., "987246351"
, how do you determine which 3 numbers constitute the solution?