【SwiftUI】今どきの データモデル (Model data) のマクロ記述 📝

ネットで参考になりそうなコード記述を探すと、

新旧入り乱れてる感じがしたので、

まず読んでおいたほうがいいような気がした。

👉 Platforms State of the Union (ASL) - WWDC23 - Videos - Apple Developer hatena-bookmark

公式ドキュメントにもしっかり説明があるようなので、ざっくり古いかもしれない記述を整理しておく。


Managing user interface state | Apple Developer Documentation
👉 https://developer.apple.com/documentation/swiftui/managing-user-interface-state

Managing model data in your app | Apple Developer Documentation
👉 https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

Migrating from the Observable Object protocol to the Observable macro | Apple Developer Documentation
👉 https://developer.apple.com/documentation/swiftui/migrating-from-the-observable-object-protocol-to-the-observable-macro

 

📝 まとめ


: ObservableObject   →   @Observable
@Published           →   不要
@StateObject         →   @State
.environmentObject() →   .environment()
@EnvironmentObject   →   @Environment
@ObservedObject      →   不要 or @Bindable

→ 「@Published*Object があれば古い。」

SwiftData を使うにしても、まずは SwiftUI のみの記述の変遷の知識もいるよな ?

先人たちの作ったネットリソースや AI系コードサジェスチョンを効率的に利用するためにも。

次は SwiftData です。


【Xcode】Refactor - Rename ができない - Rename failed ✏️

これ。

どうやら、


~/Library/Developer/Xcode/DerivedData

を消せば良いそうです。

👉 【Xcode】Auto-Completion がおかしい 不具合の理由 → DerivedData hatena-bookmark
👉 Xcodeでリファクタリングに失敗するRename failed #Swift - Qiita hatena-bookmark

 

✏️ Behavors に登録しておく

すぐに忘れて毎回調べているので忘れないように登録しておきます。

まず、スクリプトファイルを作成しておいて、


#!/usr/bin/env bash

rm -rf ~/Library/Developer/Xcode/DerivedData
afplay /System/Library/Sounds/Glass.aiff

左上メニュー Xcode から Behavior に追加。

実行してから音がなるまで結構時間がかかるので、

結構な量のファイルが削除されていることが分かります。

 

✏️ まとめ

あと、

消した DerivedData は再び自動で作成される

Clean Build Folder では DerivedData は消えません

とのことです。


【Swift】Optional 型を使っても「nil」を書きたくない 🤔

みんな大嫌いな「nil」。

できればコード内に「nil」と書きたくありません。

見るのも嫌ですね!

あんまり高度な記述もアレなので、

初心者らしく調べてみました。

 

🤔 サンプルコード

スタートはこんなかんじです。


let age: Int? = nil

if age != nil {
  if age >= 18 {
    print("成人")
  }
}

エラーです。

 

🤔 OK な記述

以下、すべて等価。


if age != nil && age! >= 18 {
  print("成人")
}


if age != nil {
  if age! >= 18 {
    print("成人")
  }
}


if let age = age {
  if age >= 18 {
    print("成人")
  }
}

👉 【Swift初心者のための】オプショナル型と if let は何のためにあるの? #Swift - Qiita hatena-bookmark


if let _ = age {
  if age! >= 18 {
    print("成人")
  }
}


if let age {
  if age >= 18 {
    print("成人")
  }
}


if let age, age >= 18 {
  print("成人")
}

 

🤔 まとめ

nil でないことを確認してそのまま使いたい場合、


if let age {
  if age >= 18 {
    print("成人")
  }
}


if let age, age >= 18 {
  print("成人")
}

の記述は、覚えやすいし、便利に使えそう。

以下の、Apple 公式のサンプルコードが調べるきっかけになりました。

👉 sample-backyard-birds/BackyardBirdsData/Birds/Bird.swift at 1843d5655bf884b501e2889ad9862ec58978fdbe · apple/sample-backyard-birds hatena-bookmark


【#SwiftUI】レイアウトの調整に View.background(Color.*) が便利だな

もっと、いい方法があれば教えてほしいです。

連続する Modifirer の中で

パディング、マージンの調整に便利かも、

という発想。

視覚的に把握できるの便利。

View Debugger で見るより実はシンプルで速い。



慣れてしまえばどうでもいい話かな。


【Xcode】Auto-Completion がおかしい 不具合の理由 → DerivedData

なぜか、

通常プロジェクトと Playground では Auto-Completion が違う。

マルチなクロージャーを含む


Button(action:label:)

を Auto-Completion で生成して、全クロージャー展開しようとするとできない。

せっかく Playgorund で Completion の使い方を掴んだような気がしてたのに!


 

🛠️ 症状

クロージャー展開しようとすると以下の感じ。

Playground 側は OK。


// Playground

Button {
  code
} label: {
  code
}

// Button(action: <#T##() -> Void#>, label: <#T##() -> View#>)

フォーカスの当たったままコピーすると設定記述的なものがテキストで取得できる。

これが、既存プロジェクト側では、なぜか、展開できない。


// Project

Button(action: {}, label: {
        Text("Button")
 })

// Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/, label: {
//   /*@START_MENU_TOKEN@*/Text("Button")/*@END_MENU_TOKEN@*/
//    })

なんやこれ。

プロジェクト内に同様な記述があると思って探しみたけど見当たらない。

登録されている Completions を


Editor
  ↓
Show Completions

で確認しても問題はなさそう。

あれこれやっていると、直ることがある。


- Xcode 再起動直後だけ一瞬直る。
- しかし、2回目ぐらいから戻っておかしくなる。

よって、キャッシュか何かを読み込んでいる、と想像。

 

🛠️ 修正・対応方法

これでいけた。


rm -rf ~/Library/Developer/Xcode/DerivedData/*

👉 Xcode Quick Fix - Clear Cache hatena-bookmark

以下でも直ったのかもしれない。


Product

  ↓

Clean Build Folder...

  +

Option


👉 [Xcode][小ネタ] DerivedDataの削除についての備忘録 | DevelopersIO hatena-bookmark

 

🛠️ まとめ

DerivedData を削除することで効果が出る不具合。


- Build Failed
- ストレージが肥大
- Completion がおかしい

キャッシュのようなもので消しても問題ないらしい。

場所はデフォルトで、


~/Library/Developer/Xcode/DerivedData

で以下メニューから確認できる。


File

 ↓

{project name} Settings...

少し前に、Xcode をバージョンアップデートしたのでそれが影響しているのかもしれないです。