Swift : guard が便利(nilチェック if let )

広告:超オススメUnity Asset
  広告:超オススメUnity Asset

 最近、関数内で引数がオプショナル型(?がついてる型)で渡された場合などに、その値のnilチェックを行い、nilならその処理を抜け( return )、nilでなければ、その後で利用可能な定数(letで格納)を作成する guard をよく使うのでMEMO。

以下の Error? 型のnilチェックでは if let を使っていて、Swift出始めの頃からこの形でnilチェックをしていたところ、Swift2か3あたりで guard が現れてから以下のような形を例文などでもよく見かけるようになった。 guard ではよく、以下のように複数のnilチェックを同時に行ったりする。

func didLogin(_ login: LineSDKLogin, credential: LineSDKCredential?, profile: LineSDKProfile?, error: Error?) {
    
    if let _error = error {
        print("LINE Login Failed with Error: \(_error.localizedDescription) ")
        return
    }
    
    guard
        let _profile = profile,
        let _credential = credential,
        let _accessToken = _credential.accessToken
    else {
        print("Invalid Repsonse")
        return
    }
    
    print("LINE Login Succeeded")
    print("Access Token: \(_accessToken.accessToken)")
    print("User ID: \(_profile.userID)")
    print("Display Name: \(_profile.displayName)")
    print("Picture URL: \(_profile.pictureURL)")
    print("Status Message: \(_profile.statusMessage)")
    
    self.requestFirebaseAuthTokenWithLINEAccessToken(lineAccessToken: _accessToken.accessToken)
    
}

以下も例のひとつ。 notification はオプショナル型ではないものの、その中に userInfo があるかどうかわからない、さらにその userInfo の中に firebaseToken がなければ、この関数はその先へ続行できないようにしてある。

public func doAuthenticateWithFirebaseToken(_ notification: NSNotification){
    
    guard
        let _userinfo = notification.userInfo,
        let _firebaseToken = _userinfo["firebaseToken"] as? String
    else {
        print("No userInfo found in notification")
        return
    }
    
    ・・・

}

↓参考:シンプルでわかりやすい

また、↓こんな風に、条件を満たさなかった場合、fatalError() であえて強制終了させるような例も。

func openAuth(){
    let storyboard = UIStoryboard(name: "AuthView", bundle: nil)
    guard let controller = storyboard.instantiateInitialViewController() else {fatalError()}
    navigationController?.pushViewController(controller, animated: true)
}

↓参考: fatalError() について

Swiftは、その多くはObjective-CおよびCocoa Frameworkから取られているが、Swift特有の機能も少なくない。Objective-Cでは基本的にNSObjectのサブクラスとして扱われる各クラスの一方で、Swift
スポンサーリンク