【SwiftUI】Cannot invoke initializer for type 'XXX' with an argument list of type エラーへの対処法

この記事の概要

SwiftUIにおける、Cannot invoke initializer for type 'FugaFuga' with an argument list of type '(hogehoge: hogehoge)'エラーにどう対処すればいいか、について書いていきます。


目次


  • この記事の概要
  • 目次
  • やろうとしたこと
  • 発生したエラー
  • エラーの翻訳
  • 解決策
  • 参考文献

やろうとしたこと

SwiftUIを勉強しており、Listを使ったデータ表示の方法を勉強していた。参考にしていたサイトは次のサイトである:SwiftUIでListを表示するhttps://swiswiswift.com/2019-11-13/

ここに書いてあるコードを参考に、以下のコードを自分で打った。

import SwiftUI

//charcterクラス
struct character: Identifiable{
//characterクラスの中に付与したい情報の定義
    var id: Int
    let name: String
}

//Viewクラス
struct ListSampleView: View {
    //データベース(配列)の用意
    let charas: [Character] = [
        Character(id:1, name:"日向翔陽"), //このコードにCannot invoke initializer for type 'Character' with an argument list of type '(id: Int, name: String)'エラーが発生する。
        Character(id:2, name:"影山飛雄"),
        Character(id:3, name:"月島 蛍"),
        Character(id:4, name:"西谷 夕"),
        Character(id:5, name:"澤村大地"),
    ]
    
    var body: some View {


    }
}

struct ListSampleView_Previews: PreviewProvider {
    static var previews: some View {
        ListSampleView()
    }
}

発生したエラー

Cannot invoke initializer for type 'Character' with an argument list of type '(id: Int, name: String)'

エラーの翻訳

 タイプ '(id:Int、name:String)'の引数リストでタイプ 'Character'の初期化子を呼び出すことはできません


解決策

Characterの初期化子を、定義しているはずなのに呼び出せないはずがないよなー、と思いcharacterクラスにどこか間違いがあると睨み、もう一度コードを読み返した。


struct characterIdentifiable{
//characterクラスの中に付与したい情報の定義
    var idInt
    let nameString
}

あった。


struct characterIdentifiable{

characterのcが大文字ではなく小文字であったためであった。タイポミスが原因だったみたい。


struct CharacterIdentifiable{
//characterクラスの中に付与したい情報の定義
    var idInt
    let nameString
}

大文字に修正したら、エラーは消えました。

最終的なコード
import SwiftUI

//charcterクラス
struct CharacterIdentifiable{
//characterクラスの中に付与したい情報の定義
    var idInt
    let nameString
}

//Viewクラス
struct ListSampleViewView {
    //データベース(配列)の用意
    let charas: [Character] = [
        Character(id:1, name:"日向翔陽"), //このコードにCannot invoke initializer for type 'Character' with an argument list of type '(id: Int, name: String)'エラーが発生する。
        Character(id:2, name:"影山飛雄"),
        Character(id:3, name:"月島 蛍"),
        Character(id:4, name:"西谷 夕"),
        Character(id:5, name:"澤村大地"),
    ]
    
    var bodysome View {


    }
}

struct ListSampleView_PreviewsPreviewProvider {
    static var previewssome View {
        ListSampleView()
    }
}


参考文献

・SwiftUIでListを表示する
https://swiswiswift.com/2019-11-13/

コメント

このブログの人気の投稿

【Unity】シーンギズモがデフォルトで表示されない時

【Swift4】argument passed to call that takes no arguments の解決策

【Swift4】iOSシミュレータでカメラとフォトライブラリが起動しない?試してみてわかったこと