Why my 0.3 MB image occupies around 10 MB on RAM?
5 (2)

Click to rate this post!
[Total: 2 Average: 5]

You are writing an application that has a long list of entries, with each entry containing an image, the total download size of all images is about 10 MB, but the images take around 200 ~ 300 MB on RAM, you wonder why 🧐?

RAM normally does not understand images that are compressed, they are stored as raw bitmaps, even if the image is compressed, it gets inflated into memory as a raw image.

Image Size on RAM = (pixels height Γ— pixels width Γ— color depth bytes)

The following image takes around 300 KB on disk and has an sRGB color profile, which is 24 bits (8 bits per channel).

Unsplash (CC0)

The size of the image on the RAM would be:

Image Size on RAM = (1665β€Š Γ— β€Š2081 Γ— 3) bytes = 9.8MB

In Swift, Kingfisher comes with an option to downsize images according to the screen scale, so you can have images in a reasonable size even if they come largely from the server.

import UIKit
import Kingfisher

extension UIImageView {
    func setImageAsThumb(url:String) {
        let formattedURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
        let scale = UIScreen.main.scale
        let resizingProcessor = ResizingImageProcessor(referenceSize: CGSize(width: 50.0 * scale, height: 50.0 * scale))
        self.kf.setImage(with: URL(string: formattedURL), placeholder: nil, options: [.processor(resizingProcessor)])


Never Use Floating-Point / Double Data types for Money Calculations!
5 (1)

Click to rate this post!
[Total: 1 Average: 5]

Floating point values, or even (Double precision floating point format), should be avoided when using a currency amount with fractions (like Dollars and cents), in its nature, it cannot be stored exactly as is in memory.

Say we want to store 0.1 dollars, any floating-point data type can not store it as is, it get’s stored as an approximation (0.10000000149….).

When doing a series of math operations, some problem can rise, that is called (loss of significance), the errors can be amplified and cause trouble 🧐.

the solution is simple, use NSNumber

let myBalance = 12.333
let decimal: Decimal = NSNumber(floatLiteral: 12.333).decimalValue
let result = decimal / 3

Swift: The Difference Between Void and ()
5 (1)

Click to rate this post!
[Total: 1 Average: 5]

Void is a data type that is common across a lot of programming languages, in Swift’s standard library, it’s simply an empty tuple, it’s used for for functions that return nothing, when defining a function, if you don’t specify a return type, you get a function that return Void, this is how it’s defined in standard library.

public typealias Void = ()

You use Void to declare the type of a function, method, or closure, Keep in mind πŸ€“
that () can mean two things:

() can be a type – the empty tuple type, which is the same as Void.
() can be a value – an empty tuple, which is the same as Void().