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]
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
}
Try this let dir2=dir[Int((trueHeading - 22.5) / 45.0) & 7]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With