swiftswiftuiuikit

SwiftUI UIViewControllerRepresentable, what does Coordinator(self) mean?


What does Coordinator(self) mean when making a UIViewControllerRepresentable (to use a UIKit component in SwiftUI)? I am a little confused on what the “self” represents.

import SwiftUI

struct ImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?
    @Environment(\.presentationMode) var presentationMode

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePicker
        
        init(_ parent: ImagePicker) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            if let uiImage = info[.originalImage] as? UIImage {
                parent.image = uiImage
            }
            
            parent.presentationMode.wrappedValue.dismiss()
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let picker = UIImagePickerController()
        picker.delegate = context.coordinator
        return picker
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
        
    }
}

Solution

  • self always means "the current instance". So when you write...

    struct ImagePicker: UIViewControllerRepresentable {
        func makeCoordinator() -> Coordinator {
            Coordinator(self)
        }
    }
    

    ... self means "this ImagePicker instance".

    You are saying this because of the way the initializer for Coordinator is declared:

    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        var parent: ImagePicker
        init(_ parent: ImagePicker) {
            self.parent = parent
        }
    }
    

    Coordinator needs a parent in order to be initialized; you are initializing a Coordinator and you are telling it who the parent should be, namely you (i.e. self, this ImagePicker).

    If these concepts give you trouble, you might need to study up on what types and instances are (object-oriented programming) and/or how Swift initializers and initialization are expressed.