0

I have an array which is large, but doesn't need an Int with 8 Byes. So I decided to use Int32 as index. I also defined an extension to avoid error messages, that you can't use Int32 but to convert it to Int:

extension Array {
    subscript(index: Int32) -> Element? {
        get {
            if index < 0 || Int(index) >= count {
                return nil
            }
            return self[Int(index)]
        }
        set(newValue) {
            if let newValue = newValue, index >= 0 && Int(index) < count {
                self[Int(index)] = newValue
            }
        }
    }
}

Unfortunately this doesn't have any effect. Any idea?

Peter71
  • 2,180
  • 4
  • 20
  • 33
  • 3
    Why use Int32 at all? Stick with Int, it's common convention – Rob C Feb 26 '23 at 13:24
  • 1
    What exactly does not work? – Btw, the standard subscript methods do not return optionals. They throw an error if the index is out of bounds. – Martin R Feb 26 '23 at 13:28
  • 1
    "I have an array which is large, but doesn't need an Int with 8 Byes." - what does that mean ? If you use Int it will use 32 or 64 bytes depending on the current system – Petar Feb 26 '23 at 14:34
  • I can't reproduce this issue. The above (while likely not a good idea), works fine in my test. Please add an MCVE: https://stackoverflow.com/help/minimal-reproducible-example – Rob Napier Feb 26 '23 at 16:29
  • Ok, I think you are right. I use an MacBook, which uses a 64 bit OS. So when using indices for 500.000 Elements, I could have saved 2 MB of RAM. On the other hand it could slow down a little bit because of converting types. I will try the conventional way with Int. Thanks for your comments. – Peter71 Feb 27 '23 at 07:52

0 Answers0