Using Decodable in Swift 4 with Inheritance

I believe in the case of inheritance you must implement Coding yourself. That is, you must specify CodingKeys and implement init(from:) and encode(to:) in both superclass and subclass. Per the WWDC video (around 49:28, pictured below), you must call super with the super encoder/decoder. required init(from decoder: Decoder) throws { // Get our container for … Read more

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

I got rid of this warning by changing the “Swift 3 @objc Inference” build setting of my targets to “Default”. From this article: Before Swift 4, the compiler made some Swift declarations automatically available to Objective-C. For example, if one subclassed from NSObject, the compiler created Objective-C entry points for all methods in such classes. … Read more

How to decode a property with type of JSON dictionary in Swift [45] decodable protocol

With some inspiration from this gist I found, I wrote some extensions for UnkeyedDecodingContainer and KeyedDecodingContainer. You can find a link to my gist here. By using this code you can now decode any Array<Any> or Dictionary<String, Any> with the familiar syntax: let dictionary: [String: Any] = try container.decode([String: Any].self, forKey: key) or let array: … Read more

How can I use String substring in Swift 4? ‘substring(to:)’ is deprecated: Please use String slicing subscript with a ‘partial range from’ operator

You should leave one side empty, hence the name “partial range”. let newStr = str[..<index] The same stands for partial range from operators, just leave the other side empty: let newStr = str[index…] Keep in mind that these range operators return a Substring. If you want to convert it to a string, use String‘s initialization … Read more