Mathematical functions in Swift

后端 未结 6 2326
花落未央
花落未央 2020-11-30 23:04

How do I use mathematical functions like sqrt(), floor(), round(), sin(), etc?


When doing:

         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 23:54

    For people using swift [2.2] on Linux i.e. Ubuntu, the import is different!

    The correct way to do this is to use Glibc. This is because on OS X and iOS, the basic Unix-like API's are in Darwin but in linux, these are located in Glibc. Importing Foundation won't help you here because it doesn't make the distinction by itself. To do this, you have to explicitly import it yourself:

    #if os(macOS) || os(iOS)
    import Darwin
    #elseif os(Linux) || CYGWIN
    import Glibc
    #endif
    

    You can follow the development of the Foundation framework here to learn more


    EDIT: December 26th, 2018

    As pointed out by @Cœur, starting from swift 3.0 some math functions are now part of the types themselves. For example, Double now has a squareRoot function. Similarly, ceil, floor, round, can all be achieved with Double.rounded(FloatingPointRoundingRule) -> Double.

    Furthermore, I just downloaded and installed the latest stable version of swift on Ubuntu 18.04, and it looks like Foundation framework is all you need to import to have access to the math functions now. I tried finding documentation for this, but nothing came up.

    ➜ swift          
    Welcome to Swift version 4.2.1 (swift-4.2.1-RELEASE). Type :help for assistance.
      1> sqrt(9)
    error: repl.swift:1:1: error: use of unresolved identifier 'sqrt'
    sqrt(9)
    ^~~~
    
    
      1> import Foundation
      2> sqrt(9)
    $R0: Double = 3
      3> floor(9.3)
    $R1: Double = 9
      4> ceil(9.3) 
    $R2: Double = 10
    

提交回复
热议问题