손지현
손지현

Reputation: 71

Why people add .0 on CGFloat?

https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/ImplementingACustomControl.html#//apple_ref/doc/uid/TP40015214-CH19-SW1 In this tutorial,

button.widthAnchor.constraint(equalToConstant: 44.0).isActive = true

constant is typed "44.0" not "44".

Is there any difference between them?

I measured time of the methods.

func evaluateProblem(problemNumber: Int, problemBlock: () -> Void)
{
    print("Evaluating problem \(problemNumber)")

    let start = DispatchTime.now() // <<<<<<<<<< Start time
    let end = DispatchTime.now()   // <<<<<<<<<<   end time

    let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64)

    print("Time to evaluate problem \(problemNumber): \(nanoTime)")
}

evaluateProblem(problemNumber: 2) {
    let b: CGFloat = 44
    print(b)
}

evaluateProblem(problemNumber: 1) {
    let a: CGFloat = 44.0
    print(a)
}

But the faster one is not fixed.

Upvotes: 1

Views: 358

Answers (1)

Rob C
Rob C

Reputation: 5073

You can initialize Double, Float, CGFloat, Int, etc. with integer literals because all of the above conform to the ExpressibleByIntegerLiteral protocol. Behind the scenes initialization with a literal simply calls the init(integerLiteral:) method of the conforming type.

Likewise, there is a ExpressibleByFloatLiteral protocol that handles initialization with floating point literals, and that protocol has an initializer that must also be implemented by conforming types.

As far as which to use, it's a matter of personal preference and style. Both ways of initialization are valid and unless you're doing thousands of initializations the performance difference would be negligible.

Upvotes: 1

Related Questions