Friday, January 12, 2024
HomeiOS Developmentios - settle for any variable sort that can be utilized...

ios – settle for any variable sort that can be utilized in SwiftUI Textual content view


One possibility is to introduce a protocol that the generic sort should conform to and that Textual content can benefit from

protocol TextSupport {
    var textual content: String { get }
}

Then we alter the declaration of the view to

struct ReusableListView<Aspect: Hashable & TextSupport>: View

and use the property within the view

ForEach(set, id: .self) { merchandise in
    Textual content("(merchandise.textual content)")
}

Then that you must conform to the protocol for any sort you utilize

extension String: TextSupport {
    var textual content: String { self }
}
extension Int: TextSupport {
    var textual content: String { self.formatted() }
}

Another choice is so as to add a closure property to the view so that every implementation of the view passes its personal method of changing the Aspect sort to a String

var convert: (Aspect) -> String

the property is ready within the init

init(_ set: Binding<OrderedSet<Aspect>>, convert: @escaping (Aspect) -> String) {
    self._set = set
    self.convert = convert
}

and use it within the ForEach

ForEach(set, id: .self) { merchandise in
    Textual content("(convert(merchandise))")
}

And you then name the view with a closure

ReusableListView($setWithStrings) { $0 }
ReusableListView($setWithInts) { $0.formatted() }



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments