UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: What is my mistake in this simple class example

Forums > SwiftUI

@onqun  

Hello, I want to extract values from text field into my class.

class keyWord: ObservableObject {

   @Published var term: String = ""
   @Published var description: String = ""

}
struct ContentView: View {

    @ObservedObject var keyword:keyWord = keyWord()

    var body: some View {

        NavigationView {

            TextEditor("Enter the term", text: $keyword.term)

            TextEditor("Enter Description", text: $keyword.description)

        }
    }
}

3      

The :keyWord part is fine, for the same reason that :String is fine in the keyWord class. Neither are nnecessary in this example but fine if they are there.

The problem is that TextEditor only takes one parameter.

So this:

TextEditor("Enter the term", text: $keyword.term)

TextEditor("Enter Description", text: $keyword.description)

should be:

TextEditor(text: $keyword.term)

TextEditor(text: $keyword.description)

And definitely use @StateObject here instead of @ObservableObject.

Also, this isn't a problem per se, but you really should name your types with capital letters. So KeyWord instead of keyWord. The convention in Swift is to start type names with capital letters and variables with lowercase letters. It helps make your code more readable and understandable.

FYI, it helps when asking for help if you explain what problem you are seeing. Do you get an error that prevents compilation? A crash? etc. Just saying "what's my mistake" doesn't really help anyone figure things out. In this case, it was pretty simple, but it might not always be.

3      

@onqun  

thank you very much

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.