gpt4 book ai didi

swift - 如何使用swift将方向度数转换为文字?

转载 作者:搜寻专家 更新时间:2023-10-31 22:10:19 25 4
gpt4 key购买 nike

我有一个oc版本

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]}}
}

然后我转换成swift版本

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]
}

但这行不通,这行出现错误“Expected ',' separator”

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

最佳答案

你想要:

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]
}

注意,是+,不是-

或者您可以使用 rounded 来避免混淆是加还是减 22.5:

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

然后您可以像这样使用此 compassDirection 结果:

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
}

关于swift - 如何使用swift将方向度数转换为文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48118390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com