swiftswiftuipattern-matchingmapkit

Swift pattern matching error using region


I am using SWiftui and Xcode 16.2 and I am trying to get a region but getting this error . I have been searching around to see how I can resolve this but no luck

'let' binding pattern cannot appear in an expression

This is my first time trying this and I have a simple code

import Foundation
import SwiftUI
import CoreLocation
import MapKit
import UIKit

func getRegion(from position: MapCameraPosition) -> MKCoordinateRegion? {
    var result: MKCoordinateRegion? = nil
    switch position {
    case .region(let region):
        result = region
    default:
        break
    }
    return result
}

Solution

  • The error you are facing happens because pattern matching is not available for structs and you are trying to switch on a struct:

    @available(iOS 17.0, macOS 14.0, watchOS 10.0, tvOS 17.0, *)
    public struct MapCameraPosition : Equatable {
    

    Instead, you should just use MapCameraPosition's field region

    public var region: MKCoordinateRegion? { get }
    

    So you don't need a separate function for it:

    let position = MapCameraPosition.automatic
    
    let region = position.region // region