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 @ 2022-05-11 19:28  xgqfrms  阅读(30)  评论(2编辑  收藏  举报