Swift 2.0 error handling for property (get / set)

Swift 2.0 allow function error handling by using the throws keyword.

The Swift doc explain that throws is part a a function type.


Now I would like to use the same throw / try / catch mechanism to handle errors in the context of computed properties (i.e. throw an error in the get / set code).


Is this possible now ? Planned for future Swift 2.x version ?


Thanks,


Datagram

Accepted Reply

We agree that you should be able to mark the getters and setters as "throws" in subscripts and computed properties, but haven't gotten there yet. We are likely to support this at some time, but it isn't clear if it will make it in time for Swift 2.


-Chris

Replies

> Is this possible now ? Planned for future Swift 2.x version ?


I hope so - I was just trying to do exactly that, too.


For the moment I worked around it by using separate getXXX and setXXX methods instead of having a computed property. But that's not ideal

I also want this; I want to be able to stop a setter from working if they pass an invalid value to it.

As a workaround I have written an assert in a willSet method:


class Fight {
     var player1: Player
     var player2: Player
     var winner: Player? {
          willSet {
               assert(contains(newValue!), "Cannot set the winner!")
          }
     }

     init (player1: Player, player2: Player) {
          self.player1 = player1
          self.player2 = player2
     }

     func contains(player: Player) -> Bool {
          return (player === self.player1) || (player === self.player2)
     }
}

We agree that you should be able to mark the getters and setters as "throws" in subscripts and computed properties, but haven't gotten there yet. We are likely to support this at some time, but it isn't clear if it will make it in time for Swift 2.


-Chris