简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM