How to convert a degree to a compass direction in Swift

1 Answer

0 votes
/*
0°   → North
45°  → North-East
90°  → East
135° → South-East
180° → South
225° → South-West
270° → West
315° → North-West
*/

// degreesToDirection converts degrees into a compass direction.
func degreesToDirection(_ degrees: Double) -> String {
    // Normalize degrees to (0, 360)
    let normalized = (degrees + 360).truncatingRemainder(dividingBy: 360)

    // Define compass directions
    let directions = [
        "North", "North-East", "East", "South-East",
        "South", "South-West", "West", "North-West"
    ]

    // Each direction covers 45 degrees
    let index = Int((normalized + 22.5) / 45) % 8
    // Alternative: let index = Int((normalized / 45) + 0.5) % 8

    return directions[index]
}

let degrees = 120.0

print("For \(Int(degrees)) degrees, Compass direction: \(degreesToDirection(degrees))")



/*
run:

For 120 degrees, Compass direction: South-East

*/

 



answered Nov 24, 2025 by avibootz
...