Swift 4类型赋值错误:无法将CLLocationDegrees(Double)赋值给Int
Got it, let's break this down and fix this without losing that precious precision you need!
为什么会报错?
The error 'Cannot assign value of type 'CLLocationDegrees' (aka 'Double') to type 'Int'' pops up because you're trying to shove a floating-point number (which has decimal precision) into an integer variable (which only holds whole numbers). The fix doesn't have to mean losing precision—you just need to align your variable types correctly.
最直接的解决方案:改用匹配的浮点类型存储
Instead of forcing the CLLocationDegrees/Double values into Int variables, just declare your storage variables to match the type of the data you're working with. Here's how:
错误的写法(导致报错):
// 你可能不小心把变量声明成了Int var userLatitude: Int = location.coordinate.latitude var userLongitude: Int = location.coordinate.longitude var userSpeed: Int = location.speed
正确的写法(保留全精度):
You can either use Double directly (since CLLocationDegrees is just a type alias for Double), or use the Core Location type aliases for clarity:
// 方式1:用Double直接对应 var userLatitude: Double = location.coordinate.latitude var userLongitude: Double = location.coordinate.longitude var userSpeed: Double = location.speed // 方式2:用Core Location的类型别名,代码可读性更强 var userLatitude: CLLocationDegrees = location.coordinate.latitude var userLongitude: CLLocationDegrees = location.coordinate.longitude var userSpeed: CLLocationSpeed = location.speed
This way, you're storing the exact floating-point values without any conversion or precision loss.
如果必须用Int类型(比如API要求):
If you're stuck needing to pass an Int to some API or storage system, don't just truncate the decimal—scale the value to preserve precision instead:
// 把数值放大10^6倍(保留6位小数精度)转成Int let latitudeInt = Int(location.coordinate.latitude * 1_000_000) let longitudeInt = Int(location.coordinate.longitude * 1_000_000) let speedInt = Int(location.speed * 1_000_000) // 当你需要使用原始精度时,再缩小回去 let restoredLatitude = Double(latitudeInt) / 1_000_000 let restoredLongitude = Double(longitudeInt) / 1_000_000 let restoredSpeed = Double(speedInt) / 1_000_000
This trick lets you store the value as an integer while keeping almost all the original precision—perfect for cases where you can't use floating-point types directly.
额外提示:UI显示时控制精度
If you're only dealing with displaying these values (not storing them), use string formatting to show the exact number of decimal places you need instead of converting to Int:
// 保留6位小数,显示给用户 let latitudeDisplayText = String(format: "%.6f", location.coordinate.latitude) // 输出示例:"37.774929"
内容的提问来源于stack exchange,提问作者username

