Skip to content

Instantly share code, notes, and snippets.

@TheFanatr
Created March 22, 2023 16:34
Show Gist options
  • Save TheFanatr/ff841481aa45f7eaad326c02ec83e618 to your computer and use it in GitHub Desktop.
Save TheFanatr/ff841481aa45f7eaad326c02ec83e618 to your computer and use it in GitHub Desktop.
Bing Chat Generatives: SwiftUI-Provided Swift Attributes

SwiftUI provides several property wrappers that can be used for programming. Here is a list of some of them:

  • @State: This property wrapper is used to manage small amounts of value type data locally to a view. It owns its data⁵.
// Example
struct ContentView: View {
    @State private var name = ""
    
    var body: some View {
        TextField("Enter your name", text: $name)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()
    }
}
  • @Binding: This property wrapper refers to value type data owned by a different view. Changing the binding locally changes the remote data too. It does not own its data⁵.
// Example
struct ChildView: View {
    @Binding var name: String
    
    var body: some View {
        TextField("Enter your name", text: $name)
            .textFieldStyle(RoundedBorderTextFieldStyle())
            .padding()
    }
}

struct ParentView: View {
    @State private var name = ""
    
    var body: some View {
        ChildView(name: $name)
    }
}
  • @Environment: This property wrapper lets us read data from the system, such as color scheme, accessibility options, and trait collections. You can add your own keys here if you want. It does not own its data⁵.
// Example
struct ContentView: View {
    @Environment(\.colorScheme) var colorScheme
    
    var body: some View {
        Text("Hello World")
            .foregroundColor(colorScheme == .dark ? Color.white : Color.black)
            .padding()
    }
}
  • @EnvironmentObject: This property wrapper reads a shared object that we placed into the environment. It does not own its data⁵.
// Example
class UserSettings: ObservableObject {
    @Published var score = 0
}

struct ContentView: View {
    @EnvironmentObject var settings: UserSettings
    
    var body: some View {
        VStack{
            Text("Score : \(settings.score)")
                .font(.largeTitle)
                .padding()
            
            Button(action:{
                settings.score += 1
            }){
                Text("Increase Score")
                    .font(.title)
                    .foregroundColor(Color.white)
                    .padding()
                    .background(Color.blue)
                    .cornerRadius(10)
            }
        }.padding()
        
    }
}
  • @ObservedObject: This property wrapper refers to an instance of an external class that conforms to the ObservableObject protocol. It does not own its data⁵.
// Example
class UserSettings: ObservableObject {
   @Published var score = 0 
}

struct ContentView : View {

   @ObservedObject var settings = UserSettings()

   var body : some View{
       VStack{
           Text("Score : \(settings.score)")
               .font(.largeTitle)
               .padding()

           Button(action:{
               self.settings.score += 1 
           }){
               Text("Increase Score")
                   .font(.title)
                   .foregroundColor(Color.white)
                   .padding()
                   .background(Color.blue) 
                   .cornerRadius(10) 
           } 
       }.padding() 
   } 
}

Source: Conversation with Bing, 3/22/2023(1) All SwiftUI property wrappers explained and compared. https://www.hackingwithswift.com/quick-start/swiftui/all-swiftui-property-wrappers-explained-and-compared Accessed 3/22/2023. (2) swift - How to use Attributed String in SwiftUI - Stack Overflow. https://stackoverflow.com/questions/59531122/how-to-use-attributed-string-in-swiftui Accessed 3/22/2023. (3) Introducing SwiftUI | Apple Developer Documentation. https://developer.apple.com/tutorials/swiftui/ Accessed 3/22/2023. (4) Attributes | Documentation - Swift.org. https://docs.swift.org/swift-book/documentation/the-swift-programming-language/attributes/ Accessed 3/22/2023. (5) swift - What does the SwiftUI @State keyword do? - Stack Overflow. https://stackoverflow.com/questions/56438730/what-does-the-swiftui-state-keyword-do Accessed 3/22/2023. (6) SwiftUI Property Wrappers | Kodeco - raywenderlich.com. https://www.kodeco.com/21522453-swiftui-property-wrappers Accessed 3/22/2023. (7) What are SwiftUI’s property wrappers and how are they used?. https://siempay.medium.com/what-are-swiftuis-property-wrappers-and-how-are-they-used-9b848ae0ba0d Accessed 3/22/2023.

Yes, there are more property wrappers available in SwiftUI. Here are some additional ones:

  • @AppStorage: This property wrapper reads and writes values from UserDefaults. It owns its data.
// Example
struct ContentView: View {
    @AppStorage("name") var name: String = "Anonymous"
    
    var body: some View {
        VStack {
            Text("Welcome, \(name)!")
            
            Button(action: {
                self.name = "Taylor"
            }) {
                Text("Log in")
            }
        }
    }
}
  • @GestureState: This property wrapper stores values associated with a gesture that is currently in progress. It will be reset to its default value when the gesture stops. It owns its data.
// Example
struct ContentView: View {
    @GestureState private var dragOffset = CGSize.zero
    
    var body: some View {
        let drag = DragGesture()
            .updating($dragOffset) { value, state, transaction in
                state = value.translation
            }

        return Circle()
            .fill(Color.red)
            .frame(width: 64, height: 64)
            .offset(dragOffset)
            .gesture(drag)
    }
}
  • @SceneStorage: This property wrapper lets us save and restore small amounts of data for state restoration. It owns its data.
// Example
struct ContentView: View {
    @SceneStorage("selectedTab") private var selectedTab = 1
    
    var body: some View {
        TabView(selection: $selectedTab) {
            Text("First tab")
                .tabItem { Image(systemName: "1.circle") }
                .tag(0)
            
            Text("Second tab")
                .tabItem { Image(systemName: "2.circle") }
                .tag(1)
            
            Text("Third tab")
                .tabItem { Image(systemName: "3.circle") }
                .tag(2)
        }
    }
}

Yes, there are even more property wrappers available in SwiftUI. Here are some additional ones:

  • @FetchRequest: This property wrapper starts a Core Data fetch request for a particular entity. It owns its data.
// Example
struct ContentView: View {
    @FetchRequest(entity: Task.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Task.name, ascending: true)])
    var tasks: FetchedResults<Task>
    
    var body: some View {
        List(tasks, id: \.self) { task in
            Text(task.name ?? "Unknown")
        }
    }
}
  • @Published: This property wrapper is attached to properties inside an ObservableObject and tells SwiftUI that it should refresh any views that use this property when it is changed. It owns its data.
// Example
class UserSettings: ObservableObject {
    @Published var score = 0
}

struct ContentView : View {
   @ObservedObject var settings = UserSettings()

   var body : some View{
       VStack{
           Text("Score : \(settings.score)")
               .font(.largeTitle)
               .padding()

           Button(action:{
               self.settings.score += 1 
           }){
               Text("Increase Score")
                   .font(.title)
                   .foregroundColor(Color.white)
                   .padding()
                   .background(Color.blue) 
                   .cornerRadius(10) 
           } 
       }.padding() 
   } 
}
  • @ScaledMetric: This property wrapper reads the user’s Dynamic Type setting and scales numbers up or down based on an original value you provide. It owns its data.
// Example
struct ContentView: View {
    @ScaledMetric(relativeTo: .largeTitle) var imageSize: CGFloat = 100
    
    var body: some View {
        Image(systemName: "cloud.sun.rain.fill")
            .resizable()
            .frame(width: imageSize, height: imageSize)
            .foregroundColor(.blue)
    }
}

Yes, there are even more property wrappers available in SwiftUI. Here are some additional ones:

  • @StateObject: This property wrapper is used to store new instances of reference type data that conforms to the ObservableObject protocol. It owns its data.
// Example
class UserSettings: ObservableObject {
    @Published var score = 0
}

struct ContentView : View {
   @StateObject var settings = UserSettings()

   var body : some View{
       VStack{
           Text("Score : \(settings.score)")
               .font(.largeTitle)
               .padding()

           Button(action:{
               settings.score += 1 
           }){
               Text("Increase Score")
                   .font(.title)
                   .foregroundColor(Color.white)
                   .padding()
                   .background(Color.blue) 
                   .cornerRadius(10) 
           } 
       }.padding() 
   } 
}
  • @FocusedBinding: This property wrapper is designed to watch for values in the key window, such as a text field that is currently selected. It does not own its data.

  • @FocusedValue: This property wrapper is a simpler version of @FocusedBinding that doesn’t unwrap the bound value for you. It does not own its data.

These are just some examples of the many property wrappers available in SwiftUI. Each has its own specific use case and functionality.

Here are examples of using @FocusedBinding and @FocusedValue in SwiftUI:

  • @FocusedBinding: This property wrapper is designed to watch for values in the key window, such as a text field that is currently selected. It does not own its data.
// Example
struct ContentView: View {
    @State private var name = ""
    @FocusedBinding(\.isNameFieldFocused) var isNameFieldFocused
    
    var body: some View {
        VStack {
            TextField("Enter your name", text: $name)
                .focused($isNameFieldFocused)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            
            Button(action: {
                isNameFieldFocused = true
            }) {
                Text("Focus Name Field")
            }
        }
    }
}

extension FocusedValues {
    var isNameFieldFocused: Bool? {
        get { self[IsNameFieldFocusedKey.self] }
        set { self[IsNameFieldFocusedKey.self] = newValue }
    }
}

struct IsNameFieldFocusedKey: FocusedValueKey {
    typealias Value = Bool
}
  • @FocusedValue: This property wrapper is a simpler version of @FocusedBinding that doesn’t unwrap the bound value for you. It does not own its data.
// Example
struct ContentView: View {
    @State private var name = ""
    @State private var email = ""
    
    @FocusedValue(\.fieldToEdit) var fieldToEdit
    
    var body: some View {
        VStack(spacing: 20) {
            TextField("Enter your name", text: $name)
                .focused(fieldToEdit == .name ? $fieldToEdit : nil)
            
            TextField("Enter your email", text: $email)
                .focused(fieldToEdit == .email ? $fieldToEdit : nil)
            
            Button(action: { fieldToEdit = .name }) { Text("Edit Name") }
            
            Button(action: { fieldToEdit = .email }) { Text("Edit Email") }
        }.padding()
    }
}

enum FieldToEdit {
    case name
    case email
}

extension FocusedValues {
   struct FieldKey : FocusedValueKey { typealias Value = FieldToEdit? } 
   var fieldToEdit : FieldToEdit? { 
      get { self[FieldKey.self] } 
      set { self[FieldKey.self] = newValue } 
   } 
}

These are just some examples of how to use @FocusedBinding and @FocusedValue in SwiftUI.

  • Welcome back! What would you like to chat about?

Received message. 〃

  • what are the @ modifiers in Swift called

Sent message. 〃

Searching for: @ modifiers in Swift

Searching for: @ modifiers in Swift

Generating answers for you…

Generating answers for you…

Received message. 〃

  • what does the @ symbol mean in Swift

Sent message. 〃

Searching for: @ symbol meaning in Swift

Searching for: @ symbol meaning in Swift

Generating answers for you…

Generating answers for you…

Received message. 〃

  • what attributes does SwiftUI provide

Sent message. 〃

Searching for: SwiftUI attributes

Searching for: SwiftUI attributes

Generating answers for you…

Generating answers for you…

Received message. 〃

  • I meant what Swift attributes does SwiftUI provide for programming use? Present these in a list. Top-level elements should be the attribute names, with each element having an indented "sub"-paragraph containing a brief explanation of attribute functionality, with a small snippet providing the context in which it could be used, with a description comment. Minimize all other prose.

Sent message. 〃

Searching for: Swift attributes in SwiftUI

Searching for: Swift attributes in SwiftUI

Searching for: SwiftUI property wrappers

Searching for: SwiftUI property wrappers

Generating answers for you…

Generating answers for you…

Received message. A

  • There are more.

Sent message. 〃

Received message. B

  • There are yet more.

Sent message. 〃

Received message. C

  • There are still more.

Sent message. 〃

Received message. D

  • Generate the examples for the latter two.

Sent message. 〃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment