Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I find the "math, strings, etc... libraries" for Swift?

Tags:

ios

swift

cocoa

I am looking at the Swift documentation, but I can't find reference to what there's in other languages...

Examples: sin(), cos(), abs() for math, uppercase(), lowercase() for strings, sort(), pop(), push() for arrays etc...

For strings I've found this in the docs:

Swift’s String type is bridged seamlessly to Foundation’s NSString class. If you are working with the Foundation framework in Cocoa or Cocoa Touch, the entire NSString API is available to call on any String value you create, in addition to the String features described in this chapter. You can also use a String value with any API that requires an NSString instance.

Could you point me to some doc or where can I find those functions listed?

like image 289
napolux Avatar asked Jun 08 '14 17:06

napolux


People also ask

Are swift strings collections?

A string is a series of characters, such as "Swift" , that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings.

Is string a class in Swift?

Almost all of Swift's core types are implemented as structs, including strings, integers, arrays, dictionaries, and even Booleans.


2 Answers

Looks like this is working...

import Foundation
var theCosOfZero: Double = Double(cos(0))  // theCosOfZero equals 1
like image 157
napolux Avatar answered Sep 30 '22 00:09

napolux


The math functions are defined in the Darwin module, so as absolute minimum you have add this:

import Darwin

In most cases import Foundation or import Cocoa will suffice, since those modules import the Darwin module. If you need access to constants like M_PI or similar, navigate with cmd+click to the Darwin module and the to the Darwin.C. Here you would find the C API imports and the Darwin.C.math among them. This way you may examine what's available, already converted to Swift. Nevertheless, all that C API is available with import Darwin.

You cannot issue import Darwin.C.math directly, because you will see the following runtime error (or similar if you're not in the playground):

Playground execution failed: Error in auto-import:
failed to get module 'math' from AST context

Example playground code:

import Darwin

func degToRad(degrees: Double) -> Double {
    // M_PI is defined in Darwin.C.math
    return M_PI * 2.0 * degrees / 360.0
}

for deg in 0..<360 {
    sin(degToRad(Double(deg)))
}
like image 45
Maksymilian Wojakowski Avatar answered Sep 30 '22 01:09

Maksymilian Wojakowski