控制流(swift)
生活随笔
收集整理的這篇文章主要介紹了
控制流(swift)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
檢測API是否可用
if #available(iOS 9, OSX 10.10, *) {// 在 iOS 使用 iOS 9 APIs , 并且在 OS X 使用 OS X v10.10 APIs } else {// 回滾至早前 iOS and OS X 的API }?以上可用性條件指定在iOS,if段的代碼僅僅在iOS9及更高可運行;在OS X,僅在OS X v10.10及更高可運行。最后一個參數,*,是必須的并且指定在任何其他平臺上,if段的代碼在最小可用部署目標指定項目中執行。
在它普遍的形式中,可用性條件獲取了平臺名字和版本的清單。平臺名字可以是iOS,OSX或watchOS。除了特定的主板本號像iOS8,我們可以指定較小的版本號像iOS8.3以及 OS X v10.10.3。
if #available(`platform name` `version`, `...`, *) {`statements to execute if the APIs are available` } else {`fallback statements to execute if the APIs are unavailable` }?
提前退出
func greet(person: [String: String]) {guard let name = person["name"] else {return}print("Hello \(name)")guard let location = person["location"] else {print("I hope the weather is nice near you.")return}print("I hope the weather is nice in \(location).") } greet(["name": "John"]) // prints "Hello John!" // prints "I hope the weather is nice near you." greet(["name": "Jane", "location": "Cupertino"]) // prints "Hello Jane!" // prints "I hope the weather is nice in Cupertino."?相比于可以實現同樣功能的if語句,按需使用guard語句會提升我們代碼的可靠性。 它可以使你的代碼連貫的被執行而不需要將它包在else塊中,它可以使你處理違反要求的代碼接近要求。
轉載于:https://www.cnblogs.com/wlsxmhz/p/5993189.html
總結
以上是生活随笔為你收集整理的控制流(swift)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面向对象第八天---预处理与mysql事
- 下一篇: tableView里选中一行cell其它