1

我在 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()
        }
    }

转换我的错误后:

在展开 Optional 值时发现 nil。

我构建了 swift 2.3:destinationUrl = "file:///Users/admin/Library/.../Documents/test.mp3" 0x00006080002a73e0

我构建了 swift 3:destinationUrl = "file:///Users/admin/Library/.../Documents/Optional(%22test.mp3%22)"

4

1 回答 1

0

错误的来源在这一行

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

首先——但与问题无关——不要注释编译器可以推断的类型。您将一个好的非可选字符串变成了一个更糟糕的隐式展开可选字符串。

该属性lessonPath显然也是一个(隐式展开)可选。使用字符串插值你得到字面量"Optional(foo)"。如果属性可以是,则需要解包可选或使用可选绑定nil。如果值永远不能是,请考虑非可选属性nil

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

有关更多信息,请阅读带有隐式展开 Optionals 的 Swift 3 不正确的字符串插值

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

于 2016-12-19T12:45:55.030 回答