Bird
Raised Fist0
iOS Swiftmobile~20 mins

Why forms capture structured data in iOS Swift - Build It to Prove It

Choose your learning style10 modes available
Build: Simple Contact Form
This screen lets users enter their name, email, and message. When they tap Submit, the app collects the data in a structured way and shows a confirmation.
Target UI
-------------------------
| Simple Contact Form   |
|-----------------------|
| Name: _______________ |
| Email: ______________|
| Message: ____________ |
|                       |
|       [Submit]         |
-------------------------
Add three text fields: Name, Email, Message
Add a Submit button below the fields
When Submit is tapped, collect the data into a struct
Show an alert confirming the data was captured
Starter Code
iOS Swift
import SwiftUI

struct ContactFormView: View {
    // TODO: Add @State properties for name, email, message

    var body: some View {
        NavigationView {
            Form {
                // TODO: Add TextFields for Name, Email, Message

                // TODO: Add Submit button
            }
            .navigationTitle("Simple Contact Form")
        }
    }
}

struct ContactFormView_Previews: PreviewProvider {
    static var previews: some View {
        ContactFormView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

struct ContactData {
    var name: String
    var email: String
    var message: String
}

struct ContactFormView: View {
    @State private var name = ""
    @State private var email = ""
    @State private var message = ""
    @State private var showingAlert = false
    @State private var capturedData: ContactData? = nil

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Your Info")) {
                    TextField("Name", text: $name)
                        .autocapitalization(.words)
                        .disableAutocorrection(true)
                    TextField("Email", text: $email)
                        .keyboardType(.emailAddress)
                        .autocapitalization(.none)
                        .disableAutocorrection(true)
                }
                Section(header: Text("Message")) {
                    TextField("Message", text: $message)
                }
                Button("Submit") {
                    capturedData = ContactData(name: name, email: email, message: message)
                    showingAlert = true
                }
                .disabled(name.isEmpty || email.isEmpty || message.isEmpty)
            }
            .navigationTitle("Simple Contact Form")
            .alert("Data Captured", isPresented: $showingAlert) {
                Button("OK", role: .cancel) { }
            } message: {
                if let data = capturedData {
                    Text("Name: \(data.name)\nEmail: \(data.email)\nMessage: \(data.message)")
                }
            }
        }
    }
}

struct ContactFormView_Previews: PreviewProvider {
    static var previews: some View {
        ContactFormView()
    }
}

This form uses three text fields to collect user input for name, email, and message. Each field is bound to a @State variable to keep track of what the user types.

When the Submit button is tapped, the app creates a ContactData struct instance that holds the entered data in a clear, organized way. This shows how forms capture structured data, making it easy to use or send elsewhere.

An alert then confirms the data was captured by showing the entered values. The Submit button is disabled until all fields have some text, ensuring complete data.

Final Result
Completed Screen
-------------------------
| Simple Contact Form   |
|-----------------------|
| Your Info             |
| Name: John Doe        |
| Email: john@example.com|
| Message               |
| Hello, this is a test.|
|                       |
|       [Submit]         |
-------------------------

[Alert]
Data Captured
Name: John Doe
Email: john@example.com
Message: Hello, this is a test.
[OK]
User types their name, email, and message into the fields.
Submit button becomes enabled when all fields have text.
Tapping Submit collects data into a struct and shows an alert with the entered info.
User taps OK to dismiss the alert.
Stretch Goal
Add validation to check if the email entered looks like a real email before enabling Submit.
💡 Hint
Use a simple check for the presence of '@' and '.' characters in the email string.

Practice

(1/5)
1. Why do mobile apps use forms to capture user input as structured data?
easy
A. To organize input clearly and make it easy to use
B. To make the app run faster
C. To reduce the app size
D. To avoid using any user input

Solution

  1. Step 1: Understand the purpose of forms

    Forms collect user input in an organized way, grouping related fields together.
  2. Step 2: Recognize benefits of structured data

    Structured data helps the app process and validate input easily and correctly.
  3. Final Answer:

    To organize input clearly and make it easy to use -> Option A
  4. Quick Check:

    Forms = organize input clearly [OK]
Hint: Forms group data for easy use and validation [OK]
Common Mistakes:
  • Thinking forms only speed up the app
  • Believing forms reduce app size
  • Assuming forms avoid user input
2. Which Swift syntax correctly defines a struct to hold form data for a user with name and age?
easy
A. struct UserForm { var name: String; var age: Int }
B. class UserForm { name: String; age: Int }
C. struct UserForm { name = String; age = Int }
D. struct UserForm { var name; var age }

Solution

  1. Step 1: Identify correct struct syntax

    In Swift, structs use 'var' to declare properties with types, separated by semicolons or newlines.
  2. Step 2: Check each option

    struct UserForm { var name: String; var age: Int } uses correct syntax with 'var' and types. Others miss 'var', use wrong assignment, or omit types.
  3. Final Answer:

    struct UserForm { var name: String; var age: Int } -> Option A
  4. Quick Check:

    Swift struct properties need 'var' and type [OK]
Hint: Use 'var' and type inside struct for properties [OK]
Common Mistakes:
  • Omitting 'var' before property names
  • Using assignment '=' instead of type declaration
  • Confusing class and struct syntax
3. Given this Swift struct and code, what will print?
struct FormData {
  var email: String
  var subscribed: Bool
}

let data = FormData(email: "user@example.com", subscribed: true)
print(data.subscribed)
medium
A. user@example.com
B. true
C. false
D. Error: missing initializer

Solution

  1. Step 1: Understand struct initialization

    The struct FormData has two properties: email (String) and subscribed (Bool). The instance 'data' is created with email and subscribed values.
  2. Step 2: Check the print statement

    print(data.subscribed) outputs the Boolean value assigned, which is true.
  3. Final Answer:

    true -> Option B
  4. Quick Check:

    Accessing struct property prints its value [OK]
Hint: Print struct property to see its stored value [OK]
Common Mistakes:
  • Confusing property names
  • Expecting email to print instead of subscribed
  • Thinking initialization is missing
4. What is wrong with this Swift struct for form data?
struct ContactForm {
  var phone: String
  var email: String
  init(phone: String) {
    self.phone = phone
  }
}
medium
A. Properties must be optional
B. Missing initializer for 'email' property
C. Structs cannot have initializers
D. Cannot use 'self' in init

Solution

  1. Step 1: Analyze the struct properties

    ContactForm has two properties: phone and email, both non-optional Strings.
  2. Step 2: Check the initializer

    The init only sets phone, but email is not initialized, causing a compile error.
  3. Final Answer:

    Missing initializer for 'email' property -> Option D
  4. Quick Check:

    All non-optional properties must be initialized [OK]
Hint: Initialize all non-optional properties in init [OK]
Common Mistakes:
  • Forgetting to initialize all properties
  • Thinking 'self' cannot be used in init
  • Believing structs cannot have initializers
5. You want to capture a form with optional phone and mandatory email. Which struct design correctly models this to capture structured data safely?
hard
A. struct Form { var phone: String; var email: String }
B. struct Form { var phone: String; var email: String? }
C. struct Form { var phone: String?; var email: String }
D. struct Form { var phone: String?; var email: String? }

Solution

  1. Step 1: Identify optional and mandatory fields

    Phone is optional, so it should be declared as an optional String (String?). Email is mandatory, so it must be a non-optional String.
  2. Step 2: Match struct design to requirements

    struct Form { var phone: String?; var email: String } correctly uses 'var phone: String?' and 'var email: String'. Others either make email optional or phone mandatory incorrectly.
  3. Final Answer:

    struct Form { var phone: String?; var email: String } -> Option C
  4. Quick Check:

    Optional for optional fields, non-optional for required [OK]
Hint: Use '?' for optional fields only [OK]
Common Mistakes:
  • Making mandatory fields optional
  • Forgetting to mark optional fields with '?'
  • Using all non-optional properties
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard