Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use swift to convert direction degree to text?

Tags:

swift

swift4

I got a oc version

public class Heading
{
    private string[] m_names[]=new string[8] { "N","NE","E","SE","S","SW","W","NW" };
    public string this[float angle]{get{return m_names[((int)((angle-22.5f)/45.0f))&7]}}
}

Then I convert to swift version

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {        
    let trueHeading = newHeading.trueHeading
    let angle = Double.pi / 180 * trueHeading

    let dir = [ "N","NE","E","SE","S","SW","W","NW" ]
    let dir2=dir[(((trueHeading-22.5)/45.0)) as Int & 7]
}

But it is not works, there is an error "Expected ',' separator" in this line

let dir2=dir[(((trueHeading-22.5)/45.0)) as Int & 7]
like image 686
CL So Avatar asked Mar 07 '23 05:03

CL So


2 Answers

You want either:

func compassDirection(for heading: CLLocationDirection) -> String? {
    if heading < 0 { return nil }

    let directions = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
    let index = Int((heading + 22.5) / 45.0) & 7
    return directions[index]
}

Note, it's +, not -.

Or you can use rounded to avoid confusion about whether to add or subtract the 22.5:

let index = Int((heading / 45).rounded()) % 8

You can then use this compassDirection result like so:

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    guard let direction = compassDirection(for: newHeading.trueHeading) else {
        // handle lack of heading here
        return
    }

    // you can use `direction` here
}
like image 192
Rob Avatar answered Mar 20 '23 03:03

Rob


Try this let dir2=dir[Int((trueHeading - 22.5) / 45.0) & 7]

like image 24
Johannes Avatar answered Mar 20 '23 04:03

Johannes