Day 57, 58, 59 of #100DaysOfSwiftUI

Start 100DaysOfSwiftUI from 2020.Mar.18th.

Day 57, 58, 59: Project 12, part one/two/three
done with 1.5 hours

New findings: followings are new findings

  • preparing wrapped property looks great idea.
  • SwiftUI feature works well together with CoreData. cool.

Codes after challenges
ContentView.swift

@Environment(\.managedObjectContext) var moc
@State private var lastNameFilter = "A"

var body: some View {
    VStack {
        // list of matching singers
        FilteredList(filterKey: "lastName",
                     filterValue: lastNameFilter,
                     sortDescriptors: [NSSortDescriptor(key: "lastName", ascending: false)]
                     ) { (singer:Singer) in
            Text("\(singer.wrappedFirstName) \(singer.wrappedLastName)")
        }
        
        Button("Add Examples") {
            let taylor = Singer(context: self.moc)
            taylor.firstName = "Taylor"
            taylor.lastName = "Swift"

            let ed = Singer(context: self.moc)
            ed.firstName = "Ed"
            ed.lastName = "Sheeran"

            let adele = Singer(context: self.moc)
            adele.firstName = "Adele"
            adele.lastName = "Adkins"

            try? self.moc.save()
        }

        Button("Show A") {
            self.lastNameFilter = "A"
        }

        Button("Show S") {
            self.lastNameFilter = "S"
        }
    }
}

FilteredList.swift

struct FilteredList: View {
    enum MyPredicateComparator:String{
        case beginswith = "BEGINSWITH"
        case like = "LIKE"
    }
    
    var fetchRequest: FetchRequest
    var singers:FetchedResults { fetchRequest.wrappedValue }
    let content:(T) -> Content
    
    init(filterKey: String, filterValue: String,
         sortDescriptors: [NSSortDescriptor],
         @ViewBuilder content:@escaping (T) -> Content) {
        fetchRequest = FetchRequest(entity: T.entity(),
                                       sortDescriptors: sortDescriptors,
                                       predicate: NSPredicate(format: "%K BEGINSWITH %@", filterKey, filterValue))
        self.content = content
    }

    init(predicateComparator: MyPredicateComparator,
         filterKey: String, filterValue: String,
         sortDescriptors: [NSSortDescriptor],
         @ViewBuilder content:@escaping (T) -> Content) {
        fetchRequest = FetchRequest(entity: T.entity(),
                                       sortDescriptors: sortDescriptors,
                                       predicate: NSPredicate(format: "%K \(predicateComparator) %@",
                                        filterKey, predicateComparator.rawValue, filterValue))
        self.content = content
    }


    
    var body: some View {
        List(fetchRequest.wrappedValue, id: \.self) { singer in
            self.content(singer)
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です