Swift 4 Conversion error – NSAttributedStringKey: Any

Why you got this error Previously, your attributes is defined as [String: Any], where the key comes from NSAttributedStringKey as a string or NSAttributedString.Key in Swift 4.2 During the migration, the compiler tries to keep the [String: Any] type. However, NSAttributedStringKey becomes a struct in swift 4. So the compiler tries to change that to … Read more

How to asynchronous load image from a web-server in UICollectionView using NSCache

Try this one it’s Working code (Swift 4). func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:@escaping (UIImage?) -> Void){ if image != nil && imageView != nil { imageView!.image = image! } var urlcatch = imgUrl.replacingOccurrences(of: “https://stackoverflow.com/”, with: “#”) let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] urlcatch = documentpath + “https://stackoverflow.com/” + “\(urlcatch)” let image = UIImage(contentsOfFile:urlcatch) if image != nil … Read more

Difference between flatMap and compactMap in Swift

The Swift standard library defines 3 overloads for flatMap function: Sequence.flatMap<S>(_: (Element) -> S) -> [S.Element] Optional.flatMap<U>(_: (Wrapped) -> U?) -> U? Sequence.flatMap<U>(_: (Element) -> U?) -> [U] The last overload function can be misused in two ways: Consider the following struct and array: struct Person { var age: Int var name: String } let … Read more

Swift Codable with dynamic keys

Assuming you left out the { and } that would surround this block and are required for this to be valid JSON, the following is the simplest solution to getting things parsed, you really don’t need to deal with CodingKey at all since your names match the keys in the JSON, so the synthesized CodingKey … 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