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?

More than 3 years have passed since last update.

【Swift】swiftlintでUIImageの「Force Unwrapping Violation」どうするか

Posted at

はじめに

Swiftlintの警告でコードが綺麗になっていくのは大変楽しく感謝しているのですが、UIImageの「Force Unwrapping Violation」の対応方法に少し悩みました。

環境

Xcode 13.2.1
Swift 5.5.2
SwiftLint 0.46.2

警告内容

コレデス
スクリーンショット 2022-01-22 9.43.59.png

強制アンラップは使用しない方がいいということですね。

丁寧に

guard let image = UIIMage(systemName: "gearshape") else { return }

としても良いのですが、都度やるのは大変なのでどうしようかと

対応策

最初に思いついたのが、UIImageのExtensionで
swiftlint:disable にする方法です。
(微妙ですね。。。)


extension UIImage {
    // swiftlint:disable force_unwrapping
    static let gearshape = UIImage(systemName: "gearshape")!
    // swiftlint:enable force_unwrapping
}

そんなことせずに
こんな形にした方が良いのかも

extension UIImage {
    static func named(_ name: String) -> UIImage {
        if let image = UIImage(systemName: name) {
            return image
        } else {
            fatalError("Could not initialize \(UIImage.self) named \(name).")
        }
    }
}

UIImage.named("gearshape")これで警告されずに使えます👏

感想

これでほんとに良いのだろう。
別に大した問題でもないので、無視して良いことではありますが。。。

参考

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?