gpt4 book ai didi

ios - 将 swift 2.3 转换为 swift 3 错误

转载 作者:行者123 更新时间:2023-11-28 08:21:22 25 4
gpt4 key购买 nike

我在 xcode 8.2 中将 swift 2.3 转换为 swift 3

swift 2.3:有代码吗,有代码吗,有代码吗,有代码吗,有代码吗

func playAudio() {
self.stopAudio()
let lessonObject:LessonObject = self.lessonArray[self.selectedIndex] as! LessonObject
let fullPath:String! = Constants.URL_HOST + "\(lessonObject.lessonPath)"
let soundURL:NSURL! = NSURL.init(string:fullPath)
let documentsDirectoryURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let destinationUrl = documentsDirectoryURL.URLByAppendingPathComponent(soundURL.lastPathComponent!)
if NSFileManager().fileExistsAtPath(destinationUrl!.path!) {
if let soundData = NSData(contentsOfFile: destinationUrl!.path!) {
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
return
}

if let soundData = NSData(contentsOfURL:NSURL(string:fullPath)!) {
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
}

swift 3:代码有没有错误?

        func playAudio() {
self.stopAudio()
let lessonObject:LessonObject = self.lessonArray[self.selectedIndex] as! LessonObject
let fullPath:String! = Constants.URL_HOST + "\(lessonObject.lessonPath)"
let soundURL:URL! = URL.init(fileURLWithPath: fullPath)
let documentsDirectoryURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
let destinationUrl = documentsDirectoryURL.appendingPathComponent(soundURL.lastPathComponent)
if FileManager().fileExists(atPath: destinationUrl.path){
if let soundData = try? Data(contentsOf: URL(fileURLWithPath: destinationUrl.path))
{
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
return
}
if let soundData = try? Data(contentsOf: URL(string:fullPath)!)
{
self.initAudioWithData(soundData)
}
else {
self.audioErrorAction()
}
}

转换后我的错误:

found nil while unwrapping an Optional value.

I build swift 2.3: destinationUrl = "file:///Users/admin/Library/.../Documents/test.mp3" 0x00006080002a73e0

I build swift 3: destinationUrl = "file:///Users/admin/Library/.../Documents/Optional(%22test.mp3%22)"

最佳答案

错误的根源在这一行

let fullPath:String! = Constants.URL_HOST + "\(lessonObject.lessonPath)"

首先——尽管与问题无关——不要注释编译器可以推断的类型。您将一个好的非可选字符串变成了一个较差的隐式解包可选字符串。

属性 lessonPath 显然也是一个(隐式解包)可选的。使用 String Interpolation 你会得到文字 "Optional(foo)"。如果属性可能为 nil,则需要解包可选或使用可选绑定(bind)。如果值永远不能为 nil

,请考虑非可选属性
let fullPath = Constants.URL_HOST + "\(lessonObject.lessonPath!)"

有关更多信息,请阅读 Swift 3 incorrect string interpolation with implicitly unwrapped Optionals

永远不要将属性声明为隐式展开的可选值 避免编写初始化程序

关于ios - 将 swift 2.3 转换为 swift 3 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com