> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/type/prop/computed-properties/local-computed-variables.md).

# local computed variables

Source: <https://www.objc.io/blog/2018/04/10/local-vars/>

Sometimes we want to compute the same expression twice in a function. For example, here’s a simplified version of some XML parsing code we recently wrote:

```swift
func parseElement(name: String, text: String) {
    if name == "trk" {
        let t = text.trimmingCharacters(in: .whitespaces)  // process element
    } else if name == "ele" {
        let elevationText = text.trimmingCharacters(in: .whitespaces)
        guard let elevation = Int(elevationText) else { return }
    } else {
        // no need to trim text
    }
}
```

Note that we’ve duplicated the`text.trimmingCharacters(in: .whitespaces)`in two branches. Of course, we can easily pull it out into a variable outside of the`if`statement:

```swift
func parseElement(name: String, text: String) {    
    let trimmed = text.trimmingCharacters(in: .whitespaces)
    if name == "trk" {
        let t = trimmed
        // process element
    } else if name == "ele" {
        guard let elevation = Int(trimmed) else { return }
    } else {
        // no need to trim text
    }
}
```

This works fine, except that it can really slow down our parsing code: we’re trimming the text for \_every \_element that we parse, but we only really need it in case of`trk`and`ele`elements. If`trimmed`were a struct or class property, we could write`lazy`in front of it, but alas, that doesn’t work for a local variable.

Instead, we can make`trimmed`a local computed property, like so:

```swift
func parseElement(name: String, text: String) {
    var trimmed: String { text.trimmingCharacters(in: .whitespaces) }
    if name == "trk" {
        let t = trimmed
        // process element
    } else if name == "ele" {
        guard let elevation = Int(trimmed) else { return }
    } else {
        // no need to trim text
    }
}
```

This will compute`trimmed`only when you need it. Of course, this solution has its drawbacks, too: if you access the`trimmed`computed property more than once, it also computes the value more than once. You have to be careful to only use it when you need it, and if you do need it multiple times, cache the value.

The technique above can also work well for complicated loop conditions. For example, here’s a completely made-up while loop with three conditions:

```swift
while !done && queue.count>1 && queue[1] != "stop" {
    // process the queue
}
```

If we want to group the two queue-related conditions into one, a local computed property can be used:

```swift
var canContinue: Bool { return queue.count > 1 && queue[1] != "stop" }

while !done && canContinue {
    // process the queue
}
```

For more advanced tricks with local properties, watch[Swift Talk 61](https://talk.objc.io/episodes/S01E61-mutable-shared-structs-part-1)and[Swift Talk 63](https://talk.objc.io/episodes/S01E63-mutable-shared-structs-part-2), where we use Swift 4’s KeyPaths to build a new hybrid type, combining useful features of both classes and structs — a fun way to push the limits of the language!


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swift/type/prop/computed-properties/local-computed-variables.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
