Error using Codable for NSAttributedString - swift

I'm trying to implement Codable for a class which contains a NSAttributedString, but I get errors at compile time:
try container.encode(str, forKey: .str)
error ambiguous reference to member 'encode(_:forKey:)'
and
str = try container.decode(NSMutableAttributedString.self, forKey: .str)
error: No 'decode' candidates produce the expected contextual type 'NSAttributedString'
I can get around it by using the NSData from the string, but thought this should work I would have thought
class Text : Codable {
var str : NSAttributedString
enum CodingKeys: String, CodingKey {
case str
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(str, forKey: .str). <-- error ambiguous reference to member 'encode(_:forKey:)'
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
str = try container.decode(NSMutableAttributedString.self, forKey: .str) <-- error: No 'decode' candidates produce the expected contextual type 'NSAttributedString'
}
}

NSAttributedString doesn’t conform to Codable, so you can’t do this directly.
If you just want to store the data you can implement a simple wrapper around your attributed string that conforms to Codable and use that in your data class. This is rather easy since you can convert the attributed string to Data using data(from:documentAttributes) when encoding. When decoding you first read the data and then initialize your attributed string using init(data:options:documentAttributes:). It supports various data formats including HTML, RTF and Microsoft Word.
Resist the temptation to add a Codable conformance to NSAttributedString in an extension. This will cause trouble when Apple adds this conformance or you add another library that does this.
If, on the other hand, you need this to communicate with a server or some other program, you need to exactly match the required data format. If you only need a plain string you probably should not use NSAttributedString at all. If it is some other format like markdown you could implement a wrapper that does the necessary transforms.

If you want to decode&encode the textual content only and convert it back from/to NS(Mutual)AttributedString you can try something like that:
class Text : Codable {
var str : NSMutableAttributedString?
enum CodingKeys: String, CodingKey {
case str
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encode(str?.string, forKey: .str)
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let content = try? container.decode(String.self, forKey: .str){
str = NSMutableAttributedString(string: content)
// ADD any attributes here if required...
}
}
}

Related

How do I (simply) "do something else" to the resulting struct after the JSONDecoder().decode does it's job?

Very simply, I have this:
public struct SomeAPI: Codable {
public let a: String
public let b: String
public let c: String
public let d: String
}
and I of course do this ...
let s = try? JSONDecoder().decode(SomeAPI.self, from: data)
Imagine I'm decoding a few hundred of those, perhaps in an array.
Very simply, after each one is decoded, I want to run some code.
So conceptually something like ..
public struct SomeAPI: Codable {
init-something() {
super.something = magic
print("I just decoded one of the thingies! a is \(a)")
}
public let a: String
public let b: String
public let c: String
public let d: String
}
I'm afraid I have absolutely no idea how to do that, having searched much. How is it done? It seems a shame to do it manually as a separate step.
The Encoding and Decoding Custom Types documentation is a great starting point for understanding how to implement the Encodable and Decodable method requirements to add to your types — and specifically, the Encoding and Decoding Manually section shows how to override the compiler-synthesized implementation of these methods to provide your own.
It's important to understand how the automated approach to Codable works, though. In a nutshell: for a type that adopts Encodable/Decodable, the compiler checks whether it's provided its own implementation of the associated method, and if not, attempts to fill it in on its own. There's no magic there: it fills in its internal state (manipulating the AST) with an implementation as if you had written it yourself in code.
For your example SomeAPI type, the generated code inside of the compiler looks exactly as if you had typed the following in yourself:
struct SomeAPI: Codable {
let a: String
let b: String
let c: String
let d: String
private enum CodingKeys: String, CodingKey {
case a, b, c, d
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
a = try container.decode(String.self, forKey: .a)
b = try container.decode(String.self, forKey: .b)
c = try container.decode(String.self, forKey: .c)
d = try container.decode(String.self, forKey: .d)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(a, forKey: .a)
try container.encode(b, forKey: .b)
try container.encode(c, forKey: .c)
try container.encode(d, forKey: .d)
}
}
This only happens if you haven't implemented the protocol requirement yourself, though: if you have, the compiler leaves the existing implementation alone, assuming you've done exactly what you want.
This last point is relevant to your use-case, because it sounds like what you'd like to do is implement this type like
struct SomeAPI: Codable {
let a: String
let b: String
let c: String
let d: String
init(from decoder: Decoder) throws {
somehowCallTheCompilerSynthesizedImplementationOfThisMethod()
/* perform some other stuff */
}
}
The issue is that when you provide your own init(from:) implementation, the compiler won't synthesize anything for your type, so there's no "default" implementation to call; unfortunately, it's an all-or-nothing deal.
To do this, then, you can either:
Implement init(from:) on your types by implementing the full method, then adding whatever code you'd like, or
Inherit the compiler-synthesized implementation in a bit of a roundabout way: if you turn SomeAPI into a class, you can allow it to receive the default synthesized implementation, then override the synthesized implementation to do what you want (demonstrated here by moving its contents into a "dummy" parent type, then keep using SomeAPI as a subclass):
class _SomeAPI: Codable {
let a: String
let b: String
let c: String
let d: String
}
class SomeAPI: _SomeAPI {
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
/* do whatever */
}
}
The downside of this approach, of course, is that this changes the semantics of the SomeAPI type, which may very well not be what you want
Approach (1) is likely a good starting approach as it keeps the semantics of this type the same, and there are tools out there that can help automatically output code for a given Swift type (e.g. Sourcery) if this gets repetitive.

Trying to make a class codable in Swift but it is not the correct format?

I am creating a class that conforms to codable.
I have this:
import Foundation
class Attribute : Decodable {
var number: Int16
var label: String?
var comments: String?
init(number:Int16, label:String?, comments:String?) {
self.number = number
self.label = label
self.comments = comments
}
// Everything from here on is generated for you by the compiler
required init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
number = try keyedContainer.decode(Int16.self, forKey: .number)
label = try keyedContainer.decode(String.self, forKey: .label)
comments = try keyedContainer.decode(String.self, forKey: .comments)
}
enum CodingKeys: String, CodingKey {
case number
case label
case comments
}
}
extension Attribute: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(number, forKey: .number)
try container.encode(label, forKey: .label)
try container.encode(comments, forKey: .comments)
}
}
This is apparently fine.
I create an instance of Attribute and encode it using:
let newAttribute = Attribute.init(number:value.number, label:value.label, comments:value.shortcut)
Then I create an array of these attributes and encode that array using
let array = try JSONEncoder().encode(array)
This will encode the array of Attribute to Data.
Then I try to convert the Data object back to the array of Attribute using this:
let array = try JSONDecoder().decode(Attribute.self, from: data) as! Array<Attribute>
First error I get is this:
Cast from 'Attribute' to unrelated type 'Array< Attribute>' always fails
If I remove the cast part I catch this error when the decode tries...
Optional("The data isn’t in the correct format.")
Any ideas?
You need to pass in the array to decode, don't pass in the array element type, then try to force-cast that to an array, that doesn't make any sense. YourType and Array<YourType> are two different and completely unrelated types, so you cannot cast one to the other and you need to use the specific type when calling JSONDecoder.decode(_:from:).
let array = try JSONDecoder().decode([Attribute].self, from: data)
Btw as already pointed out in your previous question, there is no need to manually write the init(from:) and encode(to:) methods or the CodingKeys enum since for your simple type, the compiler can auto-synthesise all of those for you. Also, if you used a struct instead of class, you'd also get the member wise initialiser for free.

Decode a Swift type that is a wrapped Codable type with an extra Codable property

I've got a Codable type, let's say Car, that is defined as:
struct Car: Codable {
let age: Int
let color: String
}
I can encode/decode this just fine.
With my persistence system, when an object is stored it gets assigned an _id property, which is a String, e.g. 5cae04b533376609456d40ed.
As such, when I read the Data from the persistent store and then try to decode it there are extra bytes in there that represent the _id property and its associated String value.
I'm not in control of the various types that can be encoded and stored in the store. The only restriction on them is that they are Codable.
What I want to be able to do is decode the Data that I get when reading from the store (with the _id stuff included) into a type that is something like Wrapped<T: Codable>, which would be defined as something like (in the simplest form):
struct Wrapped<T: Codable> {
let _id: String
let value: T
}
However, I'm not sure to go about this.
One attempt I made was to to define a custom decode function but that didn't get very far as I can't seem to access the T type's CodingKeys, which makes things, as far as I can tell, impossible with that approach.
Maybe there's another approach that would make things work as I'd like?
You can write a custom decode function for your Wrapped type that parses out the _id and then passes the decoder along to the wrapped type so it can decode it's own properties:
struct Wrapped<T: Codable>: Decodable {
let _id: String
let value: T
private enum CodingKeys: String, CodingKey {
case _id
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
_id = try container.decode(String.self, forKey: ._id)
value = try T(from: decoder)
}
}
You can simply declare that the _id property shouldn't decoded by defining your custom CodingKeys and omitting _id from there. You also need to assign a default value to the non-decoded properties (_id in your case) if you want to use the automatically synthetised initializer.
For a concrete type:
struct Car: Codable {
let age: Int
let color: String
let _id:Int = 0
enum CodingKeys: String, CodingKey {
case age, color
}
}
You can achieve this for all your persisted types.
If you don't want to create the CodingKeys enum for all persisted types, you could follow the generic wrapper type approach you started, but you'll need to create custom init(from:) and encode(to:) methods.
struct Persisted<T: Codable>: Codable {
let _id:Int = 0
let value:T
init(from decoder:Decoder) throws {
value = try decoder.singleValueContainer().decode(T.self)
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(value)
}
}

Swift Codable protocol with Strings and UIImages

I am trying to save data via a codable protocol. It is an array of structures with structs inside. There are strings, images and bool values and I am thinking it is one of these data types that does not conform to the protocol.
Here is a pic of all the data I must save:
original
struct Checklist {
var name: String
var image: UIImage?
var items: [Item] = []
}
struct Item {
var nameOfNote: String
var remind: Bool
//var date: Date
}
struct alldata: Codable {
var checklists: [Checklist] = []
}
I have tried to include the protocol in all the structs but it also produced an error. Here's a pic:
tried a solution picture
JSON in Swift 4 is fun (repeat this at 2am in the morning ;)).
One of the first things I always do is consult a good blog, like Ultimate Guide to JSON Parsing with Swift 4. While it might not answer the "direct" question, it will provide a lot of useful information.
Another thing to do, is consult the Apple documentation. In this, a quick look at the documentation for UIImage will point out that it does not conform to Codable, so that's a problem.
Another issue is, JSON doesn't support binary data, it's a text based solution.
This means that you need to figure out away to convert the binary image data to text. Lucky for us, people have already thought about this and the most common mechanism is to use Base 64 encoding.
A quick google search will turn up any number of solutions for encoding/decoding a UIImage to/from base 64, for example Convert between UIImage and Base64 string
Now, we just need to customise the encoding and decoding process.
The first thing is to make sure all the other fields/objects/data we use are also conform to Codable...
struct Item: Codable {
var nameOfNote: String
var remind: Bool
//var date: Date
}
Then we can set out customising the encoding and decoding process for the image, maybe something like...
struct Checklist: Codable {
enum CodingKeys: String, CodingKey {
case image
case name
case items
}
var name: String
var image: UIImage?
var items: [Item] = []
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
items = try container.decode([Item].self, forKey: .items)
if let text = try container.decodeIfPresent(String.self, forKey: .image) {
if let data = Data(base64Encoded: text) {
image = UIImage(data: data)
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let image = image, let data = image.pngData() {
try container.encode(data, forKey: .image)
}
try container.encode(name, forKey: .name)
try container.encode(items, forKey: .items)
}
}
nb: This is the basic process I've used for a couple of projects, I've not tested the above myself, but it should present the basic idea you need to get started

How can I decode when I don't know the type, with class inheritance?

I have a base class Action, which is an Operation. It has a bunch of crufty Operation stuff in it (KVO and all that). The base class itself doesn't actually need to encode/decode anything.
class Action : Operation, Codable {
var _executing = false
...
}
I have a bunch of Action sub-classes, like DropboxUploadAction, which are directly instantiated with an Input struct they define:
let actionInput = DropboxUploadAction.Input.init(...)
ActionManager.shared.run(DropboxUploadAction.init(actionInput, data: binaryData), completionBlock: nil)
Here's what the subclasses look like:
class DropboxUploadAction : Action {
struct Input : Codable {
var guid: String
var eventName: String
var fileURL: URL?
var filenameOnDropbox: String
var share: Bool
}
struct Output : Codable {
var sharedFileLink: String?
var dropboxPath: String?
}
var input: Input
var output: Output
...
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
input = try values.decode(Input.self, forKey: .input)
output = try values.decode(Output.self, forKey: .output)
let superDecoder = try values.superDecoder()
try super.init(from: superDecoder)
}
fileprivate enum CodingKeys: String, CodingKey {
case input
case output
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(input, forKey: .input)
try container.encode(output, forKey: .output)
try super.encode(to: container.superEncoder())
}
}
When some situations occur such as a loss of internet connectivity, these classes need to be serialized to disk for later. That's fine, because at the time I have references to them and can encode them with JSONEncoder().encode(action), no problem.
But later when I want to deserialize them, I need to specify the type of the class and I don't know what it is. I have some data and I know it can be decoded to a class that inherits from Action, but I don't know which subclass it is. I'm loathe to encode that in the filename. Is there some way to decode it as the base class Action, then in the decode() method of Action, somehow detect the proper class and redirect?
In the past I've used NSKeyedUnarchiver.setClass() to handle this. But I don't know how to do that with Swift 4's Codable, and I understand that NSCoding is deprecated now so I shouldn't use NSKeyedUnarchiver anymore...
If it helps: I have a struct Types : OptionSet, Codable which each subclass returns, so I don't have to use the name of the class as its identity.
Thanks for any help!
Uhhh NSCoding isn't deprecated. We still use it when instantiating UIViewControllers from storyboard via init(coder:).
Also, if you still don't want to use NSCoding, you can just store the Input, Output and Types to a struct and serialize that to disk instead.
struct SerializedAction {
let input: Input
let output: Output
let type: Type
}
When needed, you can decode that and decide the correct Action to initialize with your input/output via the type property.
class DropboxAction: Action {
...
init(input: Input, output: Output) {
...
}
}
You don't necessarily need to encode the entire Action object.