[swift-evolution] Proposal: Allow Getters and Setters to Throw

Nikolai Vazquez nvazquez1297 at gmail.com
Sat Dec 5 21:08:30 CST 2015


One of the aspects of Swift that I like is computed properties for
structures and classes. It allows for adding logic when obtaining values or
for having the returned value be dependent on another.

As of the `ErrorType` protocol introduction in Swift 2, we can throw errors
when it comes to functions and initializers. However, this does not apply
to getters and setters.

```swift
struct File<Data> {
    var contents: Data {
        get throws { ... }
        set throws { ... }
    }
}
```

A better example would be getting and setting the current working directory
of the process:

```swift
import Foundation

extension Process {
    static var workingDirectory: String {
        get {
            let fileManager = NSFileManager.defaultManager()
            return fileManager.currentDirectoryPath
        }
        set throws {
            let fileManager = NSFileManager.defaultManager()
            guard fileManager.changeCurrentDirectoryPath(newValue) else {
                throw Error("...")
            }
        }
    }
}



```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151205/b91b2be0/attachment.html>


More information about the swift-evolution mailing list