Easiest way to find Square Root in Swift?

前端 未结 6 1858
小鲜肉
小鲜肉 2021-02-18 22:00

I have been trying to figure out how to programmatically find a square root of a number in Swift. I am looking for the simplest possible way to accomplish with as little code ne

6条回答
  •  我在风中等你
    2021-02-18 22:31

    In Swift 3, the FloatingPoint protocol appears to have a squareRoot() method. Both Float and Double conform to the FloatingPoint protocol. So:

    let x = 4.0
    let y = x.squareRoot()
    

    is about as simple as it gets.

    The underlying generated code should be a single x86 machine instruction, no jumping to the address of a function and then returning because this translates to an LLVM built-in in the intermediate code. So, this should be faster than invoking the C library's sqrt function, which really is a function and not just a macro for assembly code.

    In Swift 3, you do not need to import anything to make this work.

提交回复
热议问题