Typealias in SwiftUI
Updated:
Typealias in SwiftUI
We can use type alias in our app to create a name for an existing type so this is a great way to create sub names of existing models and types in your app that might be a little more applicable to the part of code in your app that you’re working on again it sounds hard but is is super easy and you don’t really use this too often in your apps.
import SwiftUI
// MARK: - MODEL
struct MovieModel {
let title: String
let director: String
let count: Int
}
struct TVModel {
let title: String
let director: String
let count: Int
}
struct TypealiasBootCamp: View {
// MARK: - PROPERTY
@State var item: MovieModel = MovieModel(title: "Title", director: "Jacob", count: 5)
@State var item2: TVModel = TVModel(title: "TVTitle", director: "Emma", count: 10)
// MARK: - BODY
var body: some View {
VStack {
Text(item.title)
Text(item.director)
Text("\(item.count)")
Divider()
Text(item2.title)
Text(item2.director)
Text("\(item2.count)")
} //: VSTACK
}
}
- To avoid same model property between MovieModel and TVModel to use Typealias
TV model actually equal to the type of movie model It’s basically creating a new name for existing type This come more in handy when you have larger applications so if there’s like a section of your code where you want to refer to a specific type as something other than the actual name maybe you had like a user struct and then in one part of your code you wanted to refer to the user as customer instead of a user well you could create typealias of customer and set it equal to type user
import SwiftUI
// MARK: - MODEL
struct MovieModel {
let title: String
let director: String
let count: Int
}
typealias TVModel = MovieModel
struct TypealiasBootCamp: View {
// MARK: - PROPERTY
@State var item: MovieModel = MovieModel(title: "Title", director: "Jacob", count: 5)
@State var item2: TVModel = TVModel(title: "TVTitle", director: "Emma", count: 10)
// MARK: - BODY
var body: some View {
VStack {
Text(item.title)
Text(item.director)
Text("\(item.count)")
Divider()
Text(item2.title)
Text(item2.director)
Text("\(item2.count)")
} //: VSTACK
}
}
🗃 Reference
SwiftUI Thinking - https://www.youtube.com/watch?v=jEpg2SYvVV8&list=PLwvDm4VfkdpiagxAXCT33Rkwnc5IVhTar&index=19
Leave a comment