代码之家  ›  专栏  ›  技术社区  ›  CL So

如何使用swift将方向度转换为文本?

  •  4
  • CL So  · 技术社区  · 7 年前

    我有一个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]
    
    2 回复  |  直到 7 年前
        1
  •  5
  •   Rob Md Fahim Faez Abir    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
    }
    
        2
  •  2
  •   Johannes    7 年前

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