Swift conditional statement All In One
Swift conditional statement All In One
if
import Foundation
// 音频/视频
import AVFoundation
var audioPlayer: AVAudioPlayer?
func PlaySound(sound: String, type: String) {
// let path = Bundle.main.path(forResource: sound, ofType: type);
// if (path != nil) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path));
audioPlayer?.play();
} catch {
print("❌无法播放音频文件");
}
}
}
do...catch
https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID128
https://docs.swift.org/swift-book/ReferenceManual/Statements.html#ID435
https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html
?.
Swift optional chaining
Swift 可选链
https://www.runoob.com/swift/swift-optional-chaining.html
demo
import Foundation
// 音频/视频
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSound(sound: String, type: String) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path));
audioPlayer?.play();
} catch {
print("❌无法播放音频文件");
}
}
}
func playSound2(sound: String, type: String) {
let path = Bundle.main.path(forResource: sound, ofType: type);
// Optional type 'String?' cannot be used as a boolean; test for '!= nil' instead
// if (path) {
if (path != nil) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path ?? "mp3"));
// Cannot force unwrap value of non-optional type 'String'
audioPlayer?.play();
} catch {
print("❌无法播放音频文件");
}
}
}
refs
https://www.hackingwithswift.com/read/0/8/conditional-statements
https://www.programiz.com/swift-programming/if-else-statement
https://www.runoob.com/swift/swift-decision-making.html
https://www.runoob.com/swift/swift-loops.html
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/16259435.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-05-11 CSS @property All In One
2021-05-11 但行好事,莫问前程 All In One
2020-05-11 React Hooks & React Context vs Redux All In One
2020-05-11 umi
2020-05-11 learning-js-by-reading-source-codes
2017-05-11 Web Design Trends for 2017