忽略 function 回傳結果的 @discardableResult

function 可以回傳結果,但如果我們忽略它回傳的結果,就會像情人節忽略女朋友一樣,會產生可怕的警告。

func add(_ number1: Int, and number2: Int) -> Int {   return number1 + number2}override func viewDidLoad() {   super.viewDidLoad()   add(1, and: 2)}

如以上程式,add(1, and: 2) 回傳的結果被殘忍的拋棄,沒有被存在變數常數,也沒有被任何 function 使用(比方當成 print 的參數,印出回傳的結果),因此產生黃色警告 Result of call to ‘add(_:and:)’ is unused。

Xcode 好心產生警告是怕我們忘了處理 function 回傳的結果,不過如果你確定不想處理,而且不想看到警告的話,其實有個簡單的方法。

只要在 function 前加上 @discardableResult, Xcode 就不會再產生煩人的警告了。

@discardableResult func add(_ number1: Int, and number2: Int) -> Int? {   return number1 + number2}

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade