# Swift Core Cheat Sheet

Swift tilining chuqurroq tushunchalari, xotira boshqaruvi, protokollar va tizimli imkoniyatlari bo'yicha tezkor ma'lumotnoma.

---

## 1. Value Types vs Reference Types

| Xususiyat | Value Type (Struct, Enum, Tuple) | Reference Type (Class, Actor, Closure) |
|---|---|---|
| **Xotira joyi** | Stack (odatda) | Heap (ko'rsatkich esa stack'da) |
| **Nusxalash** | Qiymat nusxalanadi (Deep copy) | Manzil nusxalanadi (Shared reference) |
| **Meros olish (Inheritance)** | Yo'q (faqat Protocol conform) | Bor (Class subclassing) |
| **Mutatsiyalar** | `mutating func` talab qilinadi | Ob'yekt ichi erkin o'zgartiriladi |
| **Tenglik tekshiruvi** | `==` (Equatable) | `===` (Identical memory pointer) |

```swift
// Copy-on-Write (COW): Swift standart collection'lari (Array, Dictionary)
// faqat qiymat o'zgargandagina yangi xotira ajratadi.
var arr1 = [1, 2, 3]
var arr2 = arr1 // Hozircha bir xil xotira manziliga qarab turibdi
arr2.append(4)  // Shu yerda arr2 uchun alohida nusxa olinadi (COW)
```

---

## 2. Memory Management: ARC & Retain Cycles

Avtomatik hisoblagich (Automatic Reference Counting - ARC) faqat Reference typelar (class) uchun ishlaydi.

```swift
class Owner {
    var name: String
    var car: Car?
    init(name: String) { self.name = name }
    deinit { print("\(name) xotiradan o'chirildi") }
}

class Car {
    var model: String
    // Retain cycle'ning oldini olish uchun weak ishlatiladi
    weak var owner: Owner?
    init(model: String) { self.model = model }
    deinit { print("\(model) xotiradan o'chirildi") }
}
```

### Reference turlari:
- **`strong`**: Standart havola. Retain count +1.
- **`weak`**: Doim `var` va `Optional?`. Retain count oshirmaydi. Ob'yekt o'chganda avtomatik `nil` bo'ladi.
- **`unowned`**: Retain count oshirmaydi, lekin Optional emas. Ob'yekt o'chib ketganidan so'ng murojaat qilinsa, crash (`EXC_BAD_ACCESS`) beradi.

### Closure'larda Capture List:
```swift
class NetworkService {
    var data = "Boshlang'ich"

    func fetchData() {
        // [weak self] retain cycle'ni oldini oladi
        ApiClient.shared.get { [weak self] result in
            guard let self else { return }
            self.data = result
        }
    }
}
```

---

## 3. Protocols, Generics va `some` vs `any`

### Protocol va Opaque Types:
```swift
protocol IdentifiableEntity {
    associatedtype ID: Hashable
    var id: ID { get }
}

// 'some' (Opaque Type): Kompilyatsiya vaqtida aniq bitta tur qaytariladi
func createView() -> some View {
    Text("Salom")
}

// 'any' (Existential Type): Har qanday mos tur qabul qilinadi (quti/box ichida saqlanadi)
func process(items: [any IdentifiableEntity]) {
    // Dynamic dispatch ishlatiladi
}
```

### Protocol Composition:
```swift
typealias CodableEntity = Codable & Identifiable & Equatable
```

---

## 4. Property Wrappers

O'zgaruvchilarga get/set mantiqini inkapsulyatsiya qilib qayta ishlatish mexanizmi.

```swift
@propertyWrapper
struct Trimmed {
    private var text: String = ""
    
    var wrappedValue: String {
        get { text }
        set { text = newValue.trimmingCharacters(in: .whitespacesAndNewlines) }
    }
    
    // Projected value ($ belgisi orqali olinadi)
    var projectedValue: Bool {
        return !text.isEmpty
    }
    
    init(wrappedValue: String) {
        self.wrappedValue = wrappedValue
    }
}

// Ishlatilishi:
struct UserProfile {
    @Trimmed var username: String
}

var profile = UserProfile(username: "   azimjon   ")
print(profile.username)   // "azimjon" (bo'shliqlar olib tashlangan)
print(profile.$username)  // true (projected value)
```

---

## 5. Standart Protokollar (Standard Protocols)

```swift
struct Product: Identifiable, Equatable, Hashable, Comparable {
    let id: UUID
    let name: String
    let price: Double

    // Equatable (==)
    static func == (lhs: Product, rhs: Product) -> Bool {
        lhs.id == rhs.id
    }

    // Comparable (<)
    static func < (lhs: Product, rhs: Product) -> Bool {
        lhs.price < rhs.price
    }

    // Hashable (Set yoki Dictionary kaliti bo'lishi uchun)
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
}
```

---

## 6. Result Type va Xatoliklar

```swift
enum DataError: Error, LocalizedError {
    case notFound
    case unauthorized
    
    var errorDescription: String? {
        switch self {
        case .notFound: return "Ma'lumot topilmadi"
        case .unauthorized: return "Ruxsat yo'q"
        }
    }
}

// Result<Success, Failure>
func fetchScore(userId: String) -> Result<Int, DataError> {
    guard !userId.isEmpty else { return .failure(.notFound) }
    return .success(100)
}

// Ishlatilishi:
let result = fetchScore(userId: "123")
switch result {
case .success(let score):
    print("Ball:", score)
case .failure(let error):
    print("Xato:", error.localizedDescription)
}
```

---

## 7. `defer` Kalit So'zi

Funksiya qanday tugashidan qat'i nazar (return yoki throw), eng oxirida bajariladi.

```swift
func processFile() {
    let file = openFile()
    defer {
        // Har doim funksiya scope'dan chiqayotganda ishlaydi
        closeFile(file)
    }
    
    // Asosiy ishlov berish...
    if errorOccurred { return }
}
```

---

## 8. Pattern Matching & Control Flow

```swift
// if case / guard case
let score: Int? = 85
if case .some(let value) = score, value > 80 {
    print("A'lo: \(value)")
}

// ~= Operator (Range ichida tekshirish)
let age = 22
switch age {
case 0..<18: print("Voyaga yetmagan")
case 18...60: print("Kattalar")
default: print("Nafaqaxo'r")
}

// KeyPath
let names = products.map(\.name)
let sorted = products.sorted(by: { $0.price < $1.price })
```

---

## 9. Access Control (Ruxsat darajalari)

1. `open`: Boshqa modullardan ko'rinadi va **subclass/override** qilinishi mumkin (faqat class'lar).
2. `public`: Boshqa modullardan ko'rinadi, lekin faqat shu modul ichida subclass/override qilinadi.
3. `package`: Bitta Swift Package ichidagi barcha modullarda ko'rinadi (Swift 5.9+).
4. `internal`: Bitta modul (target) ichida to'liq ko'rinadi (default daraja).
5. `fileprivate`: Faqat o'sha yozilgan `.swift` fayl ichidagina ko'rinadi.
6. `private`: Faqat belgilangan struct/class va uning shu fayldagi extension'larida ko'rinadi.
