# Swift

## Functions

```swift
func addTwoNumbers(a:Int, b:Int) -> Int {
    return a+b;
}

print(addTwoNumbers(a: 5, b: 6))
```

Notice the **MANDATORY** typing and naming parameters

## Classes

```swift
class Rat {
    var health = 5;
}

class Bplate {
    let numberOfIngredientsICantPronounce = 50
    var m_rat: Rat?

    func checkForRat(exterminationInstruction: (Rat) -> Void) {
        if let rat = m_rat{
            exterminationInstruction(rat)
        }
    }
}
```

## Functions as parameters...

```swift
func exterminateRat(rat: Rat) {
    print("rip Remy")
    rat.health = 0
}

let myBplate = Bplate()
myBplate.m_rat = Rat()
myBplate.checkForRat(exterminationInstruction: exterminateRat)
```

## Closure

```swift
myBplate.checkForRat(exterminationInstruction: {
    (rat: Rat) in //could specifiy return type too (rat: Rat) -> Void
    print("this is why USC is the lamer school")
    rat.health = 0
})
```

## Typing

```swift
class Bird {
    func fly() {print("fly")}
}
class Swan: Bird {
    func poop() {}
}

var myBird: Bird
myBird = Swan()

if let forSureSwan = myBird as? Swan {
    forSureSwan.fly()
}

guard let data = response.result.value as? [String : Any] else {
    print("could not parse JSON")
    return
}
```

## Strings

aString.replacingOccurrences("\n", "")

#### PYTHON SPLIT

```swift
import Foundation

var str: String = "First Last"
var strArr = str.components(separatedBy: " ")
```


---

# Agent Instructions: 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:

```
GET https://openai.gitbook.io/code-cheatsheets/all/swift.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
