Search code examples
arraysswiftswiftui

Swift: array[0] vs array.first. Why they behawe differently?


I have ScrollView in LazyVGrid. Inside there is forEach cycle create views that appear. User can create new item in this scrollView. When new view is created using ScrollViewReader I observe change of custom Bool property that toggled and scroll view to top using

.onChange(of: boolProperty) { _ in
                    withAnimation {
                        reader.scrollTo(viewModel.items.[0].id, anchor: .top)
                    }
                }

and everything works fine, but if i change [0] to .first like this

.onChange(of: boolProperty) { _ in
                    withAnimation {
                        reader.scrollTo(viewModel.items.first?.id, anchor: .top)
                    }
                }

behavior isn't the same and view scrolls only a little bit and not to the top


Solution

  • first returns an optional type (returns nil when the array is empty), so viewModel.items.first?.id is of type ID?, where ID is the type of id.

    On the other hand, viewModel.items.[0].id is of the non-optional type ID. The subscript returns a non-optional type, and crashes when the array is empty.

    scrollTo scrolls to a view in the scroll view, that has the id you specified. Your views probably has non-optional IDs, so passing a value of an optional type will never match any view you have, and therefore doesn't scroll to the desired view.