A arquitetura equilibrada do aplicativo móvel prolonga a vida do projeto e dos desenvolvedores.
História
Conheça Alex. Ele precisa desenvolver um aplicativo para fazer uma lista de compras. Alex é um desenvolvedor experiente e, antes de tudo, forma os requisitos para o produto:
- A capacidade de portar o produto para outras plataformas (watchOS, macOS, tvOS)
- Regressão de aplicativo totalmente automatizada
- Suporte para IOS 13+
Alex recentemente se familiarizou com o projeto pointfree.com , onde Brandon e Stephen compartilharam seus insights sobre a arquitetura moderna de aplicativos. Foi assim que Alex descobriu sobre o Arquitecute Composable.
Arquitetura Composable
Depois de revisar a documentação da Arquitetura Composável, Alex determinou que estava lidando com uma arquitetura unidirecional que atendia aos requisitos de design. Da brochura segue:
- Dividindo o projeto em módulos;
- UI baseada em dados - a configuração da interface é determinada por seu estado;
- Toda a lógica do módulo é coberta por testes de unidade;
- Teste instantâneo de interfaces;
- Suporta iOS 13+, macOS, tvOS e watchOS;
- Suporte a SwiftUI e UIKit.
Antes de mergulhar no estudo da arquitetura, vamos dar uma olhada em um objeto como um guarda-chuva inteligente.

Como descrever o sistema pelo qual o guarda-chuva é organizado?
O sistema guarda-chuva tem quatro componentes:
. : .
. .
. .
. 10 .
composable architecture . .

? , .
UI — [];
Action — ;
State — [];
Environment — [ ];
Reducer — , [] ;
Effect — , action reducer.
( 1)

.
. , .
struct ShoppingListState {
var products: [Product] = []
}
enum ShoppingListAction {
case addProduct
}
reducer :
let shoppingListReducer = Reducer { state, action, env in
switch action {
case .addProduct:
state.products.insert(Product(), at: 0)
return .none
}
}
:
struct Product {
var id = UUID()
var name = ""
var isInBox = false
}
enum ProductAction {
case toggleStatus
case updateName(String)
}
let productReducer = Reducer { state, action, env in
switch action {
case .toggleStatus:
state.isInBox.toggle()
return .none
case .updateName(let newName):
state.name = newName
return .none
}
}
, reducer , , . reducer .
UI .
UI

iOS 13+ Composable Architecture SwiftUI, .
, Store:
typealias ShoppingListStore = Store<ShoppingListState, ShoppingListAction>
let store = ShoppingListStore(
initialState: ShoppingListState(products: []),
reducer: shoppingListReducer,
environment: ShoppingListEnviroment()
)
Store viewModel MVVM — .
let view = ShoppingListView(store: store)
struct ShoppingListView: View {
let store: ShoppingListStore
var body: some View {
Text("Hello, World!")
}
}
Composable Architecture SwiftUI. , store ObservedObject, WithViewStore:
var body: some View {
WithViewStore(store) { viewStore in
NavigationView {
Text("\(viewStore.products.count)")
.navigationTitle("Shopping list")
.navigationBarItems(
trailing: Button("Add item") {
viewStore.send(.addProduct)
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
Add item, . send(Action) .
, , :
struct ProductView: View {
let store: ProductStore
var body: some View {
WithViewStore(store) { viewStore in
HStack {
Button(action: { viewStore.send(.toggleStatus) }) {
Image(
systemName: viewStore.isInBox
? "checkmark.square"
: "square"
)
}
.buttonStyle(PlainButtonStyle())
TextField(
"New item",
text: viewStore.binding(
get: \.name,
send: ProductAction.updateName
)
)
}
.foregroundColor(viewStore.isInBox ? .gray : nil)
}
}
}
. ? .
enum ShoppingListAction {
//
case productAction(Int, ProductAction)
case addProduct
}
//
// .. ,
let shoppingListReducer: Reducer<ShoppingListState, ShoppingListAction, ShoppingListEnviroment> = .combine(
// ,
productReducer.forEach(
// Key path
state: ShoppingListState.products,
// Case path
action: /ShoppingListAction.productAction,
environment: { _ in ProductEnviroment() }
),
Reducer { state, action, env in
switch action {
case .addProduct:
state.products.insert(Product(), at: 0)
return .none
// productReducer
case .productAction:
return .none
}
}
)

. .
UI :
var body: some View {
WithViewStore(store) { viewStore in
NavigationView {
List {
//
ForEachStore(
// store
store.scope(
state: \.products,
action: ShoppingListAction.productAction
),
//
content: ProductView.init
)
}
.navigationTitle("Shopping list")
.navigationBarItems(
trailing: Button("Add item") {
viewStore.send(.addProduct)
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
150 , .
2 — (in progress)
Parte 3 - expansão da funcionalidade, adição de remoção e classificação do produto (em andamento)
Parte 4 - adicionar cache de lista e ir para a loja (em andamento)
Fontes
Lista de produtos, parte 1: github.com
Portal de autores da abordagem: pointfree.com
Fontes de Arquitetura Composável: https://github.com/pointfreeco/swift-composable-architecture