0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

何故かType 'SampleManager' does not conform to protocol 'ObservableObject'というエラーが出る

0
Posted at

状況

SwiftUIでObservableObjectを使った実装は以前にもしたことがあって、
同様の感じで実装しても、
何故か"Type 'SampleManager' does not conform to protocol 'ObservableObject'"というエラーが出ていました。

これがサンプルコードです。

Sample.swift
import SwiftUI

class SampleManager: ObservableObject {
    static let shared = SampleManager()
    
    func something() {
        // do something
    }
}

struct ContentView: View {    
    @ObservedObject var manager = SampleManager.shared
    
    var body: some View {
        Text("これはサンプルです。")
    }
}

環境

  • Xcode 26.2
  • MacOS 15.7.3

解決策と原因

解決策は簡単で、import Combineをすればよいだけでした。

原因は、iOS17以降、Xcode15以降で@Observableが導入されており、@ObservedObjectの使用が非推奨になっているためです。

Apple公式
https://developer.apple.com/documentation/SwiftUI/Migrating-from-the-observable-object-protocol-to-the-observable-macro

サンプル作成のためにXcode26で新規にプロジェクトを作って試していたので、気がつきませんでした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?