最近、関数内で引数がオプショナル型(?がついてる型)で渡された場合などに、その値の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() について
東京造形大学卒業後、マクロメディア(現アドビ)に入社。QAやテクニカルサポートマネージャーとしてFlash、DreamweaverなどのWeb製品を担当。独立後、2007年に虫カゴデザインスタジオ株式会社を設立。2021年東京三鷹を拠点に。最近は、Unity, Unity Netcode for GameObjects, CakePHP, Laravel, ZBrush, Modo, Adobe Substance 3D, Adobe Firefly, Xcode, Apple Vision Pro, Firebaseにフォーカスしています。モバイルアプリ開発情報を主としたブログ「MUSHIKAGO APPS MEMO」の中の人。