Learn Courses My Dashboard

Module 2: Lesson 3 Challenge

Here is how I solved this Brilliant Question, Comment down Below, If you have any better technique for it

//
//  ContentView.swift
//  Practice-2
//
//  Created by Sam Grover on 18/05/22.
//

import SwiftUI

struct ContentView: View {
    var array = ["Do Homework", "Make Vlog", "Go to party", "Meet Friends", "Shop Goods"]
    @State var listcreated = [String]()
    var body: some View {
        VStack{
            NavigationView{
            List(listcreated, id: \.self)
            {
                arrayelement in
                Text(arrayelement)
            }.navigationBarTitle(Text("Task"))
            }
            Button("Task") {
                let a = Int.random(in: 0...4)
                listcreated.append(array[a])
                }
            }
        }
        
}

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

Thanks for the feedback on your solution. I was stuck and it works perfectly.

1 Like

@Sam_Grover

Hi Sam,

Good to see you got this working.

Just a few tips on your coding.

  • When creating property names that have more than a singe word, make sure that you use camel case for the names which is the convention used in Swift. In other words instead of arrayelement use arrayElement and instead of listcreated use listCreated.
  • when naming let constants that you intend to use as an index value, give the name of the property a meaningful name. For example rather than a consider arrayIndex since that is what you are using it for. It just makes your code way more readable. This gets more important when you have complex code.

Good luck in your journey.

1 Like