Swift 4 approach for observeValue(forKeyPath:…)

Swift 4 introduced a family of concrete Key-Path types, a new Key-Path Expression to produce them and a new closure-based observe function available to classes that inherit NSObject. Using this new set of features, your particular example can now be expressed much more succinctly: self.observation = object.observe(\.keyPath) { [unowned self] object, change in self.someFunction() } … Read more

What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?

There’s a subtle, but important difference between these two lines of code: // Exhibit 1 foo = try container.decode(Int?.self, forKey: .foo) // Exhibit 2 foo = try container.decodeIfPresent(Int.self, forKey: .foo) Exhibit 1 will parse: { “foo”: null, “bar”: “something” } but not: { “bar”: “something” } while exhibit 2 will happily parse both. So in … Read more

UIImageJPEGRepresentation has been replaced by instance method UIImage.jpegData(compressionQuality:)

The error is telling you that as of iOS 12 the old UIImageJPEGRepresentation function has been replaced with the new jpegData method on UIImage. Change: let imageData = UIImageJPEGRepresentation(image, 0.75) to: let imageData = image.jpegData(compressionQuality: 0.75) Similarly, the use of UIImagePNGRepresentation has been replaced with pngData().

Simultaneous accesses to 0x1c0a7f0f8, but modification requires exclusive access error on Xcode 9 beta 4

I think this ‘bug’ may be a Swift 4 “feature”, specifically something they call “Exclusive access to Memory”. Check out this WWDC video. Around the 50-minute mark, the long-haired speaker explains it. https://developer.apple.com/videos/play/wwdc2017/402/?time=233 You could try turning the thread sanitizer off in your scheme settings if you’re happy to ignore it. However, the debugger is … Read more

Encode/Decode Array of Types conforming to protocol with JSONEncoder

The reason why your first example doesn’t compile (and your second crashes) is because protocols don’t conform to themselves – Tag is not a type that conforms to Codable, therefore neither is [Tag]. Therefore Article doesn’t get an auto-generated Codable conformance, as not all of its properties conform to Codable. Encoding and decoding only the … Read more

Swift 3 – find number of calendar days between two dates

In Swift 5 there is a simple one-liner to get the number of days (or any other DateComponent) between two dates: let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day Note: As pointed out in the comments, this solution measures the 24h periods and therefore requires at least 24h between dateA and dateB.