Swift addressable character map?

Hi! I'm a novice at swift programming, and this is my first time posting here. Please redirect me if my question would be better served elsewhere... Also please excuse any ignorance or misuse of terms.

I'm looking for a Swift/Cocoa function/routine that will allow me to place a character at any point in the (all-points-addresssible field (say 40x40) and have it show up on the screen. I'm trying to write a simple simulation where characters ('*' , '#', '@', etc) are used to represent entities and then I'll move them around by erasing and then placing at the next location.

Thanks for your time and consideration,
Chuck Brotman

I think, the best way would be to wrap an array inside your own struct.

enum Tile {
  case river, rock, field, empty
}
struct Board {
  let rowCount, columnCount: Int
  var values: [Tile]

  init(rows: Int, columns: Int) {
    rowCount = rows
    columnCount = columns
    values = .init(repeating: .empty, count: rows * columns)
  }

  subscript(row: Int, column: Int) {
    get {
      assert(0..<rowCount ~= row && 0..<columnCount ~= column)
      return values[columnCount * row + column]
    }
    set {
      assert(0..<rowCount ~= row && 0..<columnCount ~= column)
      values[columnCount * row + column] = newValue
    }
  }
}

or something like that. Composing it like this is pretty common trick to get the structure you want. So that whenever you use Board, you are more-or-less guaranteed to access a valid tile.

1 Like

Wow! I didnt expect such a fully flushed out example! Thank you very much! I will study it until I understand it fully! Can you give me a hint regarding the purpose/use of the assert statements??

THANKS AGAIN,
Chuck

Lantua,

Your example is great! I was asking, more specifically, how to get the array to display on the screen. . .

Say, for example, I wanted X's, O's and I's representing rock, empty and river, respecticely. How do I get swift to display it?? I was hoping there was some standard object/function in the framework that might help. I have no idea how to go about a search for such a thing or what it might be called…?

The goal would be to not have to rewrite the entire array each time a change occurs

How do you want to display it on a screen? If you are looking for a GUI experience on a Mac or iOS device, you will have to use the Apple frameworks, which can be accessed via Swift, but are not part of Swift. Even SwiftUI and Combine are still private Apple frameworks.

You can always use character output to terminal using swift print, C-interfaces, etc..

The assert statements test the logical conditions in the statement, and if it evaluates to false, it throws a fatalError. It's a test, in your case, that makes sure your pre-conditions are satisfied before proceeding to execute a statement that could cause a crash.

You might look at ncurses. It's not a Swift package, but it is a C library that can be called from Swift.