Are there any better syntax for generics? Belowed code gives me huge ugly generics definition in the beginning of view.
struct ViewUserSettings<TypeGif: ModelGifProtocol, TypeFont: ModelFontProtocol, TypeMagicText: ModelMagicTextProtocol, TypePreSetAnswer: ModelPreSetAnswerProtocol>: View where TypeGif: Hashable, TypeFont: Hashable, TypeMagicText: Hashable, TypePreSetAnswer: Hashable
I had to define Hashable inside generics otherwise compiler gives Error when I tried to use this Protocol in SwiftUI ForEach.
ModelGif.swift
// MARK: - Protocol
enum GifType: String, Codable {
case fooA = "fooA more"
case fooB = "fooB more"
case fooC = "fooC more"
// MARK: Properties
var fileName600px: String {
switch self {
case .fooA: return "fooAHQ"
case .fooB: return "fooBHQ"
case .fooC: return "fooCHQ"
}
}
var fileName80px: String {
switch self {
case .fooA: return "fooALQ"
case .fooB: return "fooBLQ"
case .fooC: return "fooCLQ"
}
}
}
protocol ModelGifProtocol: Codable {
var gif: GifType { get }
}
// MARK: - Module
struct ModelGif: ModelGifProtocol, Hashable {
// MARK: Properties
let gif: GifType
// MARK: Initialization
init(_ gif: GifType) {
self.gif = gif
}
// MARK: Static Properties
static var fooA = Self(.fooA)
static var fooB = Self(.fooB)
static var fooC = Self(.fooC)
}
ModelMagicText.swift
// MARK: - Protocol
protocol ModelMagicTextProtocol: Codable {
var id: UUID { get }
var context: String { get }
init(_ context: String, id: UUID) throws
init(_ context: String) throws
}
// MARK: - Module
struct ModelMagicText: ModelMagicTextProtocol, Hashable {
// MARK: Properties
let id: UUID
let context: String
// MARK: Initialization
init(_ context: String, id: UUID) throws {
guard context.count <= 30 else { throw ContextError.tooLong } // restricted at ViewAnimatingCircleText.modifyDynamicText()
self.context = context.uppercased()
self.id = id
}
init(_ context: String) throws {
try self.init(context, id: UUID())
}
init(_ model: ModelMagicTextProtocol) throws {
try self.init(model.context, id: model.id)
}
// MARK: Static Properties
static let defaultText = try! ModelMagicText("foooooooooooo")
}
// MARK: - Extension: ContextError
extension ModelMagicText {
enum ContextError: Error {
case tooLong
}
}
We can format that more readably using multiple lines. We can also move the Hashable constraints into the generic parameter list:
struct ViewUserSettings<
TypeGif: ModelGifProtocol & Hashable,
TypeFont: ModelFontProtocol & Hashable,
TypeMagicText: ModelMagicTextProtocol & Hashable,
TypePreSetAnswer: ModelPreSetAnswerProtocol & Hashable
>: View {
var gif: TypeGif
var font: TypeFont
var magicText: TypeMagicText
var preSetAnswer: TypePreSetAnswer
var body: some View { EmptyView() }
}
You only need a where clause when you have equality constraints, but your example code doesn't have any equality constraints.
If you change each of your model protocols to inherit from Hashable, you can eliminate the Hashable constraints entirely:
protocol ModelGifProtocol: Hashable { }
protocol ModelFontProtocol: Hashable { }
protocol ModelMagicTextProtocol: Hashable { }
protocol ModelPreSetAnswerProtocol: Hashable { }
struct ViewUserSettings<
TypeGif: ModelGifProtocol,
TypeFont: ModelFontProtocol,
TypeMagicText: ModelMagicTextProtocol,
TypePreSetAnswer: ModelPreSetAnswerProtocol
>: View {
...
There's also the question of whether you need such verbose names. Do you really need the Type and Model prefixes?
protocol GifProtocol: Hashable { }
protocol FontProtocol: Hashable { }
protocol MagicTextProtocol: Hashable { }
protocol PreSetAnswerProtocol: Hashable { }
struct ViewUserSettings<
Gif: GifProtocol,
Font: FontProtocol,
MagicText: MagicTextProtocol,
PreSetAnswer: PreSetAnswerProtocol
>: View {
var gif: Gif
var font: Font
var magicText: MagicText
var preSetAnswer: PreSetAnswer
var body: some View { EmptyView() }
}
Keep in mind that you can still refer to SwiftUI's Font type as SwiftUI.Font inside ViewUserSettings.
You didn't give any details regarding how your protocols are defined. Do you really need your own ModelFontProtocol? SwiftUI's Font is already Hashable, so if you can just use the concrete Font type, your code will be simpler. Maybe you can use concrete types in place of your other protocols too, but we can't say without seeing how they're defined.
If you're using the same set of type parameters and constraints for multiple views, there are ways to factor the common stuff out. You should edit your question to include more example code if that's the case.
Related
Edited from an earlier post to include a working subset of code:
I'm apparently not understanding how .onAppear works in SwiftUI with respect to Views inside of Navigation Links. I'm trying to use it to get paged JSON (in this case from the Pokemon API at pokeapi.co.
A minimal reproducible bit of code is below. As I scroll through the list, I see all of the Pokemon names for the first page print out & when I hit the last Pokemon on the page, I get the next page of JSON (I can see the # jump from 20, one page, to 40, two pages). My API call seems to be working fine & I'm loading a second page of Pokemon. I see their names appear & they print to the console when running in the simulator. However, even though the JSON is properly loaded into my list & I go from 20 to 40 Pokemon - a correct array of the first two pages - as I scroll past 40 it looks like the third page has loaded, creatures through 60 are visible in the List, but the console only occasionally shows an index name printing (also shown a sample of the output, below, note the values printing past 40 don't all show). The .onAppear doesn't seem to be firing as I expected past the 40th element, even though I can see 60 names showing up in the List. I was hoping to use .onAppear to detect when a new page needs to load & call it, but this method doesn't seem sound. Any hints why .onAppear isn't working as I expect & how I might more soundly handle recognizing when I need to load the next page of JSON? Thanks!
struct Creature: Hashable, Codable {
var name: String
var url: String
}
#MainActor
class Creatures: ObservableObject {
private struct Returned: Codable {
var count: Int
var next: String?
var results: [Creature]
}
var count = 0
var urlString = "https://pokeapi.co/api/v2/pokemon/"
#Published var creatureArray: [Creature] = []
var isFetching = false
func getData() async {
guard !isFetching else { return }
isFetching = true
print("🕸 We are accessing the url \(urlString)")
// Create a URL
guard let url = URL(string: urlString) else {
print("😡 ERROR: Could not create a URL from \(urlString)")
isFetching = false
return
}
do {
let (data, _) = try await URLSession.shared.data(from: url)
if let returned = try? JSONDecoder().decode(Returned.self, from: data) {
self.count = returned.count
self.urlString = returned.next ?? ""
DispatchQueue.main.async {
self.creatureArray = self.creatureArray + returned.results
}
isFetching = false
} else {
isFetching = false
print("😡 JSON ERROR: Could not decode returned data.")
}
} catch {
isFetching = false
print("😡 ERROR: Could not get URL from data at \(urlString). \(error.localizedDescription)")
}
}
}
struct ContentView: View {
#StateObject var creatures = Creatures()
var body: some View {
NavigationStack {
List {
ForEach(0..<creatures.creatureArray.count, id: \.self) { index in
NavigationLink {
Text(creatures.creatureArray[index].name)
} label: {
Text("\(index+1). \(creatures.creatureArray[index].name)")
}
.onAppear() {
print("index = \(index+1)")
if index == creatures.creatureArray.count-1 && creatures.urlString.hasPrefix("http") {
Task {
await creatures.getData()
}
}
}
}
}
.toolbar {
ToolbarItem (placement:.status) {
Text("\(creatures.creatureArray.count) of \(creatures.count)")
}
}
}
.task {
await creatures.getData()
}
}
}
Here's a sample of the output. The triple dots simply indicate order printed as expected:
🕸 We are accessing the url https://pokeapi.co/api/v2/pokemon/
index = 1
index = 2
index = 3
…
index = 37
index = 38
index = 39
index = 40
🕸 We are accessing the url https://pokeapi.co/api/v2/pokemon/?offset=40&limit=20
index = 41
index = 44
Try my fully functional example code that fetches the pokemons data as required.
The code gets the server response with the results when the PokeListView first appears (in .task {...}).
Then, as the user scrolls to the bottom of the current list, another page is fetched, until
all data is presented.
The new page fetching is triggered by checking for the last creature id displayed and if more data is available.
This is the crux of the paging. Note, you can adjust to trigger before the last creature is displayed.
As the user tap on any one of the creatures name, the details view is presented.
As the PokeDetailsView appears, the details are fetched from the server or from cache.
This alleviates the server burden.
The ApiService manages all server processing. With this approach
you are not fetching all the details before hand, only as required.
Since you are fetching data from a remote server, there will be times when you will see the progress view,
as it takes somethimes to download the data.
struct ContentView: View {
#StateObject var apiService = ApiService()
var body: some View {
PokeListView()
.environmentObject(apiService)
}
}
struct PokeListView: View {
#EnvironmentObject var apiService: ApiService
var body: some View {
NavigationStack {
List(apiService.pokeList.results) { pokemon in
NavigationLink(pokemon.name, value: pokemon.url)
// check if need to paginate
if let lastPoke = apiService.pokeList.results.last {
if pokemon.id == lastPoke.id && apiService.pokeList.next.hasPrefix("https") {
ProgressView()
.task {
do {
try await apiService.getPokemonList()
} catch {
print("---> refresh error: \(error)")
}
}
}
}
}
.navigationDestination(for: String.self) { urlString in
PokeDetailsView(urlString: urlString)
}
}
.environmentObject(apiService)
.task {
do {
try await apiService.getPokemonList()
} catch{
print(error)
}
}
}
}
struct PokeDetailsView: View {
#EnvironmentObject var apiService: ApiService
#State var urlString: String
#State var poky: Pokemon?
var body: some View {
VStack {
Text(poky?.name ?? "no name")
Text("height: \(poky?.height ?? 0)")
// ... other info
}
.task {
do {
poky = try await apiService.getPokemon(from: urlString)
} catch{
print(error)
}
}
}
}
class ApiService: ObservableObject {
var serverUrl = "https://pokeapi.co/api/v2/pokemon?limit=20&offset=0"
// the response from the server with the list of names and urls in `results`
#Published var pokeList: PokemonList = PokemonList(count: 0, results: [])
// dictionary store of Pokemons details [urlString:Pokemon]
#Published var pokemonStore: [String : Pokemon] = [:]
func getPokemonList() async throws {
guard let url = URL(string: serverUrl) else { return }
let (data, _) = try await URLSession.shared.data(from: url)
Task{#MainActor in
let morePoke = try JSONDecoder().decode(PokemonList.self, from: data)
self.pokeList.count = morePoke.count // <-- here
self.pokeList.next = morePoke.next
self.serverUrl = morePoke.next
self.pokeList.results.append(contentsOf: morePoke.results)
}
}
func getPokemon(from urlString: String) async throws -> Pokemon? {
if let poky = pokemonStore[urlString] {
// if already have it
return poky
} else {
// fetch it from the server
guard let url = URL(string: urlString) else { return nil }
let (data, _) = try await URLSession.shared.data(from: url)
do {
let poky = try JSONDecoder().decode(Pokemon.self, from: data)
Task{#MainActor in
// store it for later use
pokemonStore[urlString] = poky
}
return poky
} catch {
return nil
}
}
}
}
// MARK: - PokemonList
struct PokemonList: Codable {
var count: Int // <-- here
var next: String
var results: [ListItem] // <-- don't use the word Result
init(count: Int, results: [ListItem], next: String = "") {
self.count = count
self.results = results
self.next = next
}
}
// MARK: - ListItem
struct ListItem: Codable, Identifiable {
let id = UUID()
let name: String
let url: String
enum CodingKeys: String, CodingKey {
case name, url
}
}
struct HeldItem: Codable {
let item: Species
let versionDetails: [VersionDetail]
enum CodingKeys: String, CodingKey {
case item
case versionDetails = "version_details"
}
}
struct VersionDetail: Codable {
let rarity: Int
let version: Species
}
// MARK: - Pokemon
struct Pokemon: Codable, Identifiable {
let abilities: [Ability]
let baseExperience: Int
let forms: [Species]
let gameIndices: [GameIndex]
let height: Int
let heldItems: [HeldItem]
let id: Int
let isDefault: Bool
let locationAreaEncounters: String
let moves: [Move]
let name: String
let order: Int
let pastTypes: [String]
let species: Species
let sprites: Sprites
let stats: [Stat]
let types: [TypeElement]
let weight: Int
enum CodingKeys: String, CodingKey {
case abilities
case baseExperience = "base_experience"
case forms
case gameIndices = "game_indices"
case height
case heldItems = "held_items"
case id
case isDefault = "is_default"
case locationAreaEncounters = "location_area_encounters"
case moves, name, order
case pastTypes = "past_types"
case species, sprites, stats, types, weight
}
}
// MARK: - Ability
struct Ability: Codable {
let ability: Species
let isHidden: Bool
let slot: Int
enum CodingKeys: String, CodingKey {
case ability
case isHidden = "is_hidden"
case slot
}
}
// MARK: - Species
struct Species: Codable {
let name: String
let url: String
}
// MARK: - GameIndex
struct GameIndex: Codable {
let gameIndex: Int
let version: Species
enum CodingKeys: String, CodingKey {
case gameIndex = "game_index"
case version
}
}
// MARK: - Move
struct Move: Codable {
let move: Species
let versionGroupDetails: [VersionGroupDetail]
enum CodingKeys: String, CodingKey {
case move
case versionGroupDetails = "version_group_details"
}
}
// MARK: - VersionGroupDetail
struct VersionGroupDetail: Codable {
let levelLearnedAt: Int
let moveLearnMethod, versionGroup: Species
enum CodingKeys: String, CodingKey {
case levelLearnedAt = "level_learned_at"
case moveLearnMethod = "move_learn_method"
case versionGroup = "version_group"
}
}
// MARK: - GenerationV
struct GenerationV: Codable {
let blackWhite: Sprites
enum CodingKeys: String, CodingKey {
case blackWhite = "black-white"
}
}
// MARK: - GenerationIv
struct GenerationIv: Codable {
let diamondPearl, heartgoldSoulsilver, platinum: Sprites
enum CodingKeys: String, CodingKey {
case diamondPearl = "diamond-pearl"
case heartgoldSoulsilver = "heartgold-soulsilver"
case platinum
}
}
// MARK: - Versions
struct Versions: Codable {
let generationI: GenerationI
let generationIi: GenerationIi
let generationIii: GenerationIii
let generationIv: GenerationIv
let generationV: GenerationV
let generationVi: [String: Home]
let generationVii: GenerationVii
let generationViii: GenerationViii
enum CodingKeys: String, CodingKey {
case generationI = "generation-i"
case generationIi = "generation-ii"
case generationIii = "generation-iii"
case generationIv = "generation-iv"
case generationV = "generation-v"
case generationVi = "generation-vi"
case generationVii = "generation-vii"
case generationViii = "generation-viii"
}
}
// MARK: - Sprites
class Sprites: Codable {
let backDefault: String
let backFemale: String?
let backShiny: String
let backShinyFemale: String?
let frontDefault: String
let frontFemale: String?
let frontShiny: String
let frontShinyFemale: String?
let other: Other?
let versions: Versions?
let animated: Sprites?
enum CodingKeys: String, CodingKey {
case backDefault = "back_default"
case backFemale = "back_female"
case backShiny = "back_shiny"
case backShinyFemale = "back_shiny_female"
case frontDefault = "front_default"
case frontFemale = "front_female"
case frontShiny = "front_shiny"
case frontShinyFemale = "front_shiny_female"
case other, versions, animated
}
}
// MARK: - GenerationI
struct GenerationI: Codable {
let redBlue, yellow: RedBlue
enum CodingKeys: String, CodingKey {
case redBlue = "red-blue"
case yellow
}
}
// MARK: - RedBlue
struct RedBlue: Codable {
let backDefault, backGray, backTransparent, frontDefault: String
let frontGray, frontTransparent: String
enum CodingKeys: String, CodingKey {
case backDefault = "back_default"
case backGray = "back_gray"
case backTransparent = "back_transparent"
case frontDefault = "front_default"
case frontGray = "front_gray"
case frontTransparent = "front_transparent"
}
}
// MARK: - GenerationIi
struct GenerationIi: Codable {
let crystal: Crystal
let gold, silver: Gold
}
// MARK: - Crystal
struct Crystal: Codable {
let backDefault, backShiny, backShinyTransparent, backTransparent: String
let frontDefault, frontShiny, frontShinyTransparent, frontTransparent: String
enum CodingKeys: String, CodingKey {
case backDefault = "back_default"
case backShiny = "back_shiny"
case backShinyTransparent = "back_shiny_transparent"
case backTransparent = "back_transparent"
case frontDefault = "front_default"
case frontShiny = "front_shiny"
case frontShinyTransparent = "front_shiny_transparent"
case frontTransparent = "front_transparent"
}
}
// MARK: - Gold
struct Gold: Codable {
let backDefault, backShiny, frontDefault, frontShiny: String
let frontTransparent: String?
enum CodingKeys: String, CodingKey {
case backDefault = "back_default"
case backShiny = "back_shiny"
case frontDefault = "front_default"
case frontShiny = "front_shiny"
case frontTransparent = "front_transparent"
}
}
// MARK: - GenerationIii
struct GenerationIii: Codable {
let emerald: Emerald
let fireredLeafgreen, rubySapphire: Gold
enum CodingKeys: String, CodingKey {
case emerald
case fireredLeafgreen = "firered-leafgreen"
case rubySapphire = "ruby-sapphire"
}
}
// MARK: - Emerald
struct Emerald: Codable {
let frontDefault, frontShiny: String
enum CodingKeys: String, CodingKey {
case frontDefault = "front_default"
case frontShiny = "front_shiny"
}
}
// MARK: - Home
struct Home: Codable {
let frontDefault: String
let frontFemale: String?
let frontShiny: String
let frontShinyFemale: String?
enum CodingKeys: String, CodingKey {
case frontDefault = "front_default"
case frontFemale = "front_female"
case frontShiny = "front_shiny"
case frontShinyFemale = "front_shiny_female"
}
}
// MARK: - GenerationVii
struct GenerationVii: Codable {
let icons: DreamWorld
let ultraSunUltraMoon: Home
enum CodingKeys: String, CodingKey {
case icons
case ultraSunUltraMoon = "ultra-sun-ultra-moon"
}
}
// MARK: - DreamWorld
struct DreamWorld: Codable {
let frontDefault: String
let frontFemale: String?
enum CodingKeys: String, CodingKey {
case frontDefault = "front_default"
case frontFemale = "front_female"
}
}
// MARK: - GenerationViii
struct GenerationViii: Codable {
let icons: DreamWorld
}
// MARK: - Other
struct Other: Codable {
let dreamWorld: DreamWorld
let home: Home
let officialArtwork: OfficialArtwork
enum CodingKeys: String, CodingKey {
case dreamWorld = "dream_world"
case home
case officialArtwork = "official-artwork"
}
}
// MARK: - OfficialArtwork
struct OfficialArtwork: Codable {
let frontDefault: String
enum CodingKeys: String, CodingKey {
case frontDefault = "front_default"
}
}
// MARK: - Stat
struct Stat: Codable {
let baseStat, effort: Int
let stat: Species
enum CodingKeys: String, CodingKey {
case baseStat = "base_stat"
case effort, stat
}
}
// MARK: - TypeElement
struct TypeElement: Codable {
let slot: Int
let type: Species
}
Let's say that you don't really need SwiftUI features. I.e. you don't have import SwiftUI in your file. Instead, you only require
import protocol SwiftUI.UIViewControllerRepresentable
In general, you're going to have to involve a delegate object: an AnyObject at best, and usually, because the UIKit APIs are old, an NSObject.
The common pattern is to use a Coordinator class for that, and have the View itself be a struct, but is there always point in that indirection?
Here's an example which hasn't given me any trouble in practice:
import Combine
import MultipeerConnectivity
import protocol SwiftUI.UIViewControllerRepresentable
extension MCBrowserViewController {
final class View: NSObject {
init(
serviceType: String,
session: MCSession,
peerCountRange: ClosedRange<Int>? = nil
) {
self.serviceType = serviceType
self.session = session
self.peerCountRange = peerCountRange
}
private let serviceType: String
private unowned let session: MCSession
private let peerCountRange: ClosedRange<Int>?
private let didFinishSubject = CompletionSubject()
private let wasCancelledSubject = CompletionSubject()
}
}
// MARK: - internal
extension MCBrowserViewController.View {
var didFinishPublisher: AnyPublisher<Void, Never> { didFinishSubject.eraseToAnyPublisher() }
var wasCancelledPublisher: AnyPublisher<Void, Never> { wasCancelledSubject.eraseToAnyPublisher() }
}
// MARK: - private
private extension MCBrowserViewController {
typealias CompletionSubject = PassthroughSubject<Void, Never>
}
// MARK: - UIViewControllerRepresentable
extension MCBrowserViewController.View: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> MCBrowserViewController {
let browser = MCBrowserViewController(
serviceType: serviceType,
session: session
)
browser.delegate = self
if let peerCountRange = peerCountRange {
browser.minimumNumberOfPeers = peerCountRange.lowerBound
browser.maximumNumberOfPeers = peerCountRange.upperBound
}
return browser
}
func updateUIViewController(_: MCBrowserViewController, context _: Context) { }
}
// MARK: - MCBrowserViewControllerDelegate
extension MCBrowserViewController.View: MCBrowserViewControllerDelegate {
func browserViewControllerDidFinish(_: MCBrowserViewController) {
didFinishSubject.send()
}
func browserViewControllerWasCancelled(_: MCBrowserViewController) {
wasCancelledSubject.send()
}
}
I don't have a full detailed answer for your question, but your solution have some problems.
In SwiftUI, if we update a View, it calls init to recreate the View, and then call updateUIViewController.
In your case, whenever you update your View, not only your view is recreated, your two subjects will be recreated too, so anything attaches to the Publisher after the recreation won't receive events any more.
maybe that's the reason we prefer to use Coordinator.
However, getting an error message that says that my class 'Expenses' does not conform to protocol 'Decodable' & Type 'Expenses' does not conform to protocol 'Encodable'
import Foundation
class Expenses : ObservableObject, Codable {
#Published var items : [ExpenseItem] {
// Step 1 creat did set on publsihed var.
didSet {
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(items) {
UserDefaults.standard.set(encoded, forKey: "Items")
}
}
}
init() {
if let items = UserDefaults.standard.data(forKey: "Items") {
let decoder = JSONDecoder(
if let decoded = try?
decoder.decode([ExpenseItem].self, from: items) {
self.items = decoded
return
}
}
self.items = []
}
}
my expense item is flagged as
struct ExpenseItem : Identifiable, Codable {
let id = UUID()
let name : String
let type : String
let amount : Int
}
Conformance to Encodable/Decodable is auto-synthesized when all stored properties conform to Encodable/Decodable, but using a property wrapper on a property means that now the property wrapper type needs to conform to Encodable/Decodable.
#Published property wrapper doesn't conform. It would have been nice to just implement conformance on the Published type itself, but unfortunately it doesn't expose the wrapped value, so without using reflection (I've seen suggestions online), I don't think it's possible.
You'd need to implement the conformance manually:
class Expenses : ObservableObject {
#Published var items : [ExpenseItem]
// ... rest of your code
}
extension Expense: Codable {
enum CodingKeys: CodingKey {
case items
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.items, forKey: .items)
}
required init(from decoder: Decoder) throws {
var container = try decoder.container(keyedBy: CodingKeys.self)
self.items = try container.decode([ExpenseItem].self, forKey: .items)
}
}
I am exploring SwiftUI+Combine with a demo app BP Management.
Homescreen has a provision to take bp readings(systolicBP, diastolicBP, pulse & weight).
Button "Next" is enabled only when all 4 fields are filled.
control should fall to the next textfield when a valid input is entered. (input is valid when it falls between the range specified by the placeholder - refer the image below)
On tapping next, on the detail screen user can edit the bp values (taken in the HomeScreen), additionally he can add recorded date, notes...
Thought enums would be best model this so I proceeded like
enum SBPInput: CaseIterable {
//name is a Text to indicate the specific row
typealias Field = (name: String, placeholder: String)
case spb, dbp, pulse, weight, note, date
var field: Field {
switch self {
case .dbp: return ("DBP", "40-250")
case .spb: return ("SBP", "50-300")
case .pulse: return ("Pulse", "40-400")
case .weight: return ("Weight", "30-350")
case .note: return ("Note", "")
case .date: return ("", Date().description)
}
}
// Here I am getting it wrong, - I can't bind a read only property
var value: CurrentValueSubject<String, Never> {
switch self {
case .date:
return CurrentValueSubject<String, Never>(Date().description)
case .spb:
return CurrentValueSubject<String, Never>("")
case .dbp:
return CurrentValueSubject<String, Never>("")
case .pulse:
return CurrentValueSubject<String, Never>("")
case .weight:
return CurrentValueSubject<String, Never>("70")
case .note:
return CurrentValueSubject<String, Never>("")
}
}
}
class HomeViewModel: ObservableObject {
#Published var aFieldsisEmpty: Bool = true
var cancellable: AnyCancellable?
var dataSoure = BPInput.allCases
init() {
var bpPublishers = (0...3).map{ BPInput.allCases[$0].value }
//If a field is empty, we need to disable "Next" button
cancellable = Publishers.CombineLatest4(bpPublishers[0], bpPublishers[1], bpPublishers[2], bpPublishers[3]).map { $0.isEmpty || $1.isEmpty || $2.isEmpty || $3.isEmpty }.assign(to: \.aFieldsisEmpty, on: self)
}
}
The idea is to create HStacks for each datasorce(sbp,dbp,pulse,weight) to look like this
struct HomeScreen: View {
#ObservedObject var viewModel = HomeViewModel()
var body: some View {
VStack {
ForEach(Range(0...3)) { index -> BPField in
BPField(input: self.$viewModel.dataSoure[index])
}
Button("Next", action: {
print("Take to the Detail screen")
}).disabled(self.viewModel.aFieldsisEmpty)
}.padding()
}
}
struct BPField: View {
#Binding var input: BPInput
var body: some View {
//implicit HStack
Text(input.field.name)
BPTextField(text: $input.value, placeHolder: input.field.name)//Error:- Cannot assign to property: 'value' is a get-only property
// input.value being read only I can't bind it. How to modify my model now so that I can bind it here?
}
}
And my custom TextField
struct BPTextField: View {
let keyboardType: UIKeyboardType = .numberPad
var style: some TextFieldStyle = RoundedBorderTextFieldStyle()
var text: Binding<String>
let placeHolder: String
// var onEdingChanged: (Bool) -> Void
// var onCommit: () -> ()
var background: some View = Color.white
var foregroundColor: Color = .black
var font: Font = .system(size: 14)
var body: some View {
TextField(placeHolder, text: text)
.background(background)
.foregroundColor(foregroundColor)
.textFieldStyle(style)
}
}
your problems are not there, what SwiftUI tells you.
but you should first compile "small parts" of your code and simplify it, so the compiler will tell you the real errors.
one is here:
BPTextField(text: self.$viewModel.dataSoure[index].value, placeHolder: viewModel.dataSoure[index].field.placeholder)
and the error is:
Cannot subscript a value of type 'Binding<[BPInput]>' with an argument of type 'WritableKeyPath<_, _>'
and of course you forgot the self ....
I'm curious about the default implementation of AnyView in SwiftUI. How to put structs with different generic types into a protocol array?
For example:
let a = AnyView(Text("hello"))
let b = AnyView(Image(systemName: "1.circle"))
let genericViews = [a, b] // No compile error
And my implementation:
struct TypeErasedView<V: View>: View {
private var _view: V
init(_ view: V) {
_view = view
}
var body: V {
_view
}
}
let a = TypeErasedView(Text("Hello"))
let b = TypeErasedView(Image(systemName: "1.circle"))
let genericViews = [a, b] // compile error
The compile error will be "Heterogeneous collection literal could only be inferred to '[Any]'; add explicit type annotation if this is intentional".
Does anyone have any ideas?
Here is a demo of possible approach. It is simplified, but shows the generic idea of how this might be done... or at least a direction.
Full compilable & working module. Tested on Xcode 11.2 / iOS 13.2
import SwiftUI
private protocol TypeErasing {
var view: Any { get }
}
private struct TypeEraser<V: View>: TypeErasing {
let orinal: V
var view: Any {
return self.orinal
}
}
public struct MyAnyView : View {
public var body: Never {
get {
fatalError("Unsupported - don't call this")
}
}
private var eraser: TypeErasing
public init<V>(_ view: V) where V : View {
eraser = TypeEraser(orinal: view)
}
fileprivate var wrappedView: Any { // << they might have here something specific
eraser.view
}
public typealias Body = Never
}
struct DemoAnyView: View {
let container: [MyAnyView]
init() {
let a = MyAnyView(Text("Hello"))
let b = MyAnyView(Image(systemName: "1.circle"))
container = [a, b]
}
var body: some View {
VStack {
// dynamically restoring types is different question and might be
// dependent on Apple's internal implementation, but here is
// just a demo that it works
container[0].wrappedView as! Text
container[1].wrappedView as! Image
}
}
}
struct DemoAnyView_Previews: PreviewProvider {
static var previews: some View {
DemoAnyView()
}
}
It's because there's a generic constraint on yours. AnyView has no generic constraint. You instantiate it with an underlying generic View, but its Body is always declared as Never. There might be compiler magic happening here as I couldn't get a generic constraint-less version to work.