xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

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, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(30)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用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
点击右上角即可分享
微信分享提示