Learn Courses My Dashboard

Module 2: Lesson 9 Challenge

It was an easy Question, but want to ask, how we can change the text element area and How we can declare a list first and then , add all other elements, May You please HELP

The Solution of the code:

//
//  ContentView.swift
//  Practice-6
//
//  Created by Sam Grover on 23/05/22.
//

import SwiftUI

struct ContentView: View {
    @State var array: Array? = [String]()
    var body: some View {
        HStack{
            VStack{
                Button("Nill") {
                    array = nil
                }
                Button("Add") {
                    array?.append("Sam")
                    array?.append("Tam")
                    array?.append("Fam")
                }
                if array == nil{
                    Text("Please Tap on Second Button to add elements")
                    
                }else{
                    NavigationView{
                        List((array)!, id: \.self){ r in
                            Text(r)
                        }
                    }
                }
            }
            }
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Hi Sam,

When declaring an array as optional the declaration should look like this:

@State var optionalArray: [String]?

It means that right at the outset the array is nil and can be set to nil if the array has elements.

Given that the array has been declared as Optional, in order to add items to the array you must initialise it to an empty array.

array = []
OR
array = [String]()

In your Add button code you then need to test for the array being nil and if so initialise it and then append the 3 items to it.

1 Like

Solution after correction, Thanks a lot for Helping, It means a lot when there is one for helping :innocent:

//
//  ContentView.swift
//  Practice-6
//
//  Created by Sam Grover on 23/05/22.
//

import SwiftUI

struct ContentView: View {
    @State var array: [String]?
    var body: some View {
        HStack{
            VStack{
                Button("Nill") {
                    array = nil
                }
                Button("Add") {
                    if array == nil{
                        array = []
                        array?.append("Sam")
                        array?.append("Tam")
                        array?.append("Fam")
                    }
                }
                if array == nil{
                    Text("Please Tap on Second Button to add elements")
                    
                }else{
                    NavigationView{
                        List((array)!, id: \.self){ r in
                            Text(r)
                        }
                    }
                }
            }
            }
        }
    }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}