Swift - Correct syntax for "onChange" in Apple's sample code?

Hi everyone,

I wanted to create a Table and make its rows sortable. For lack of better ideas how to do this I followed Apple's example here [https://developer.apple.com/documentation/swiftui/table)

Here's the code in question:

    @State private var sortOrder = [KeyPathComparator(\Person.givenName)]


    var body: some View {
        Table(people, sortOrder: $sortOrder) {
            TableColumn("Given Name", value: \.givenName)
            TableColumn("Family Name", value: \.familyName)
            TableColumn("E-Mail address", value: \.emailAddress)
        }
        .onChange(of: sortOrder) {
            people.sort(using: $0)
        }
    }
}

To my amazement Xcode shows this message:

'onChange(of:perform:)' was deprecated in macOS 14.0: Use onChange with a two or zero parameter action closure instead.

I find this message rather annoying. Do you have any ideas how to fix this?

Answered by Claude31 in 771602022

Really surprising change (still works for iOS)

I changed as follows to make it work by using 2 parameters in closure:

        .onChange(of: sortOrder, initial: false) {val, cond  in
            people.sort(using: val)
        }

This works as well

        .onChange(of: sortOrder) {val, _ in
            people.sort(using: val)
        }

Accepted Answer

Really surprising change (still works for iOS)

I changed as follows to make it work by using 2 parameters in closure:

        .onChange(of: sortOrder, initial: false) {val, cond  in
            people.sort(using: val)
        }

This works as well

        .onChange(of: sortOrder) {val, _ in
            people.sort(using: val)
        }

Swift - Correct syntax for "onChange" in Apple's sample code?
 
 
Q