从Swift 3迁移至Swift 5.1时遇报错:'MKCoordinateRegionMake'不可用
Hey there! I’ve faced this exact error when moving Swift 3 code up to Swift 5.1, so I totally get where you’re coming from.
The issue here is that MKCoordinateRegionMake is an Objective-C-style factory function, and starting from Swift 3, Apple shifted towards using native Swift initializers for MapKit types instead. This makes the code more consistent with Swift’s overall syntax.
替换方案
Instead of using the old C-style function, you’ll want to use the Swift initializer for MKCoordinateRegion directly:
原来的Swift 3代码:
let region = MKCoordinateRegionMake(centerCoordinate, span)
修改后的Swift 5.1代码:
let region = MKCoordinateRegion(center: centerCoordinate, span: span)
额外补充:处理基于距离的区域初始化
If you were using MKCoordinateRegionMakeWithDistance (another common Objective-C helper), that also has a Swift-native replacement:
旧代码:
let region = MKCoordinateRegionMakeWithDistance(centerCoordinate, latitudinalDistance, longitudinalDistance)
新代码:
let region = MKCoordinateRegion(center: centerCoordinate, latitudinalMeters: latitudinalDistance, longitudinalMeters: longitudinalDistance)
小提示
Xcode usually shows a quick fix suggestion when you hover over the deprecated function—just click the "Fix" button and it’ll auto-replace it with the correct Swift syntax. But if that doesn’t pop up for some reason, the manual replacement above works perfectly.
内容的提问来源于stack exchange,提问作者Omar Castaño

