iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

Unable to infer complex closure return type; add explicit type to disambiguateの対処方

本日はSwift初学者向けの Unable to infer complex closure return type; add explicit type to disambiguate の対処法を簡単に紹介します🍺

結論

これはクロージャの戻り値の方をSwiftコンパイラが上手く型推論できないときに発生します。

        let itemLayouts = $0.items.map { item in // Unable to infer complex closure return type; add explicit type to disambiguate
            let layoutItem = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(1.0)))
            layoutItem.contentInsets = .init(top: 10, leading: 12, bottom: 10, trailing: 12)
            return layoutItem
        }

ということで、いずれかの方法で型を明確に宣言してあげましょう🏃‍♂️

まずは、変数に宣言するパターン。

        let itemLayouts: [NSCollectionLayoutItem] = $0.items.map { item in
            let layoutItem = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(1.0)))
            layoutItem.contentInsets = .init(top: 10, leading: 12, bottom: 10, trailing: 12)
            return layoutItem
        }

mapの戻り値を明確に宣言するパターン。

        let itemLayouts = $0.items.map { item -> NSCollectionLayoutItem in
            let layoutItem = NSCollectionLayoutItem(layoutSize: .init(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(1.0)))
            layoutItem.contentInsets = .init(top: 10, leading: 12, bottom: 10, trailing: 12)
            return layoutItem
        }

てな感じで本日も以上となります🍺

その他の記事

yamatooo.blog

yamatooo.blog

yamatooo.blog