private
를 주로 붙임// 사용예시
@State private var str = “hello”
//값이 변경되지 않는 변수
private var str = “hello”
// 사용예시
@Binding var str: String
Class
에서 사용가능@ObservableObject
: 관찰 가능한 객체@ObservedObject
: 관찰 된 객체// Observe 사용예시 코드
class MyProfile: ObservableObject {
@Published var name = "kim"
@Published var age = 0
func changeProfiel() {
self.age = 30
self.name = "min"
}
}
struct ContentView: View {
@ObservedObject var profile = MyProfile();
var body: some View {
VStack {
Text("age \(self.profile.age)")
Text("name \(self.profile.name)")
Button(action: {
self.profile.changeProfiel()
}) {
Text("Click me")
}
}
}
}
struct locationInfo: Hashable {
var city = "";
var weather = "";
}
ForEach에서 id 값을 self로 하기 위해선
Hashable
을 같이 적용시켜줘야 한다.
@State private var locationArr = [
locationInfo(city: "c1", weather: "w1"),
locationInfo(city: "c2", weather: "w2"),
locationInfo(city: "c3", weather: "w3")
];
ForEach(locationArr, id: \.self) {
location in HStack {
Text("\(location.city)")
Text("\(location.weather)")
}
}
각 생성되는 객체를 id 값을 기준으로 구별하기 때문에 id 값을 지정해 줘야 한다.
struct locationInfo: Identifiable {
var id = UUID();
var city = "";
var weather = "";
}
Identifiable
를 같이 선언해주고, id 속성 값을 넣어준다.
위 코드에서
UUID()
함수는 난수 key값을 생성해주는 함수이다.
ForEach(locationArr) {
location in HStack {
Text("\(location.city)")
Text("\(location.weather)")
}
}
// index 0,1,2,3,4
ForEach(0..<5) {
index in
Text("text \(index)")
}
// index 0,1,2,3,4,5
ForEach(0..5) {
index in
Text("text \(index)")
}
ForEach(0..<locationArr.count) {
index in
Text("text\(locationArr[index].city)")
}
sort 사용예시)
.sorted(by: { $0.idx < $1.idx })
Swift에서는 첫번째 전달받는 값을
$0
으로 표시하고 그다음 전달받는 값은$1
으로 표시한다. $뒤에 그 다음 숫자를 계속 더한값을 표시한다.
전체코드)
//
// ContentView.swift
// swift-ui-learn
//
// Created by 김부민 on 2021/08/27.
//
import SwiftUI
struct animal: Identifiable {
var id = UUID();
var name = "";
var idx = 0;
}
struct ContentView: View {
var animalArr = [
animal(name: "dog", idx: 2),
animal(name: "tiger", idx: 9),
animal(name: "cat", idx: 6),
animal(name: "bird", idx: 8),
animal(name: "cat", idx: 4),
animal(name: "dog", idx: 1),
animal(name: "cat", idx: 5),
animal(name: "bird", idx: 7),
animal(name: "cat", idx: 3),
];
var animalGroupd: [String: [animal]] {
var group = Dictionary(grouping: animalArr) {
$0.name
}
for(key,value) in group {
group[key]=value.sorted(by: { $0.idx < $1.idx })
}
return group;
}
var groupKey: [String] {
animalGroupd.map({ $0.key })
}
var body: some View {
VStack(){
List{
ForEach(groupKey, id:\.self) {
key in
Section(header:Text("\(key)")) {
ForEach(animalGroupd[key]!) {
ani in
Text("\(ani.name) \(ani.idx)")
}
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}