How to Reuse Struct on Swift? or Is There Any Other Way

Can we reuse struct on Swift? Or is there any other way?

You could use generics.

struct Response<T: Decodable>: Decodable {
let results: Result<T>
let status: Int
}

struct Result<T: Decodable>: Decodable {
let meta: Meta
let objects: [T]
}

struct Meta: Decodable {
let total_data: Int
let total_page: Int
}

struct User: Decodable {
let avatar_url: String
let created_at: String
let updated_at: String
let email: String
let id: Int
let name: String
let username: String
}

let userResponse: Response<User>?

Where to put my Struct to keep classes independent?

Put your struct in a separate file and document for each class you want to reuse that it depends on this struct. So basically you make your struct reusable as well.

The process of reusing your class becomes a little bit harder - you also have to include it’s dependencies. But that is just a fact of life, basically all software has dependencies. To make it easier to add some code dependency manages such as Cocoapods, Carthage or the Swift Package Manager have been invented. With those you specify for each library what it depends on - so ClassA depends on StructA. In the project you want to use ClassA you specify only that dependency and the package manager installs all of it’s dependencies (and their dependencies and so on) together.

Reuse Extension for multiple types

You just need extension to View, like

extension View {
func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
ModifiedContent(content: self, modifier: style)
}
}

func ExpandingTextEditor<Style: ViewModifier>(text: Binding<String>, style: Style) -> some View {
ZStack {
TextEditor(text: text)
.textStyle(style)

Text(text.wrappedValue)
.textStyle(style)
.opacity(0)
.padding(.all, 8)
}
}

or if you want to limit to only specific views:

protocol TextStyle {}

extension Text: TextStyle {}
extension TextEditor: TextStyle {}

extension View where Self: TextStyle {
func textStyle<Style: ViewModifier>(_ style: Style) -> some View {
ModifiedContent(content: self, modifier: style)
}
}

Tested with Xcode 13.3 / iOS 15.4



Related Topics



Leave a reply



Submit