繁体   English   中英

Swift 4 Codable:无法排除属性

[英]Swift 4 Codable: Cannot exclude a property

我正在开发一个简单的音乐音序器应用程序。 这种应用程序倾向于具有必须保存/加载的复杂数据结构,因此在Swift4中引入Codable协议对我来说完全是个好消息。

我的问题是:我必须有一个非编码属性。 它不必进行编码,因为它是一个临时变量,仅在应用程序处于活动状态时才保持活动状态。 因此,我只是尝试通过实现CodingKey进行排除,但是编译器仍然给我错误“类型'Song'不符合协议'Decodable'”。

具体来说,我想在下面的代码中排除“ musicSequence”。

class Song : Codable { //Type 'Song' does not conform to protocol 'Decodable'
    var songName : String = "";    
    var tempo : Double = 120;

    // Musical structure
    var tracks : [Track] = [] // "Track" is my custom class, which conforms Codable as well    
    // Tones
    var tones = [Int : ToneSettings] (); // ToneSettings is also my custom Codable class

    var musicSequence : MusicSequence? = nil; // I get the error because of this line

    private enum CodingKeys: String, CodingKey {
        case songName
        case tempo
        case tracks
        case tones
    }

    func createMIDISequence () {
        // Create MIDI sequence based on "tracks" above
        // and keep it as instance variable "musicSequence"
    }
}

有人有什么想法吗?

(请参阅下面的一些奇怪的事件。)

您对CodingKeys使用已经在进行编码。 您仍然可以免费获得。 但是您需要告诉系统如何手动处理解码:

required init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    songName = try values.decode(String.self, forKey: .songName)
    tempo = try values.decode(Double.self, forKey: .tempo)
    tracks = try values.decode([Track].self, forKey: .tracks)
    tones = try values.decode([Int: ToneSettings].self, forKey: .tones)
}

这不是足够聪明弄清楚, musicSequence可以而且应该默认为nil (也许这将是太聪明了反正)。

可能需要在bugs.swift.org上打开一个缺陷,要求该Decodable是自动的。 如果您提供CodingKeys并且有默认值,它应该能够弄清楚。


编辑:当我第一次回答这个问题时,我正好重复了您的错误。 但是,当我再次尝试将代码重新复制时,该错误不会出现。 以下代码编译并在游乐场中运行:

import Foundation

struct Track: Codable {}
struct ToneSettings: Codable {}
struct MusicSequence {}

class Song : Codable { //Type 'Song' does not conform to protocol 'Decodable'
    var songName : String = "";
    var tempo : Double = 120;

    // Musical structure
    var tracks : [Track] = [] // "Track" is my custom class, which conforms Codable as well
    // Tones
    var tones = [Int : ToneSettings] (); // ToneSettings is also my custom Codable class

    var musicSequence : MusicSequence? = nil; // I get the error because of this line

    private enum CodingKeys: String, CodingKey {
        case songName
        case tempo
        case tracks
        case tones
    }

    func createMIDISequence () {
        // Create MIDI sequence based on "tracks" above
        // and keep it as instance variable "musicSequence"
    }
}

let song = Song()
let data = try JSONEncoder().encode(song)
String(data: data, encoding: .utf8)

let song2 = try JSONDecoder().decode(Song.self, from: data)

我想知道这里是否有编译器错误; 确保使用新的Beta进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM