This article is noted practice about create modular in iOS project of JARNBOY.
In article I create SwiftPackage name BaseUI
for separate common base UI in app use display how to setup for use in main module you can try do follow this blog.
OK start!!!
Create new project
Create a new Swift Package
- Open your project and create a new Swift package by selecting
File > New > Package….
2. Named your new module. In this case, I named it “BaseUI”.
Noted: Don’t forget select your main project root folder as the destination and add the new package to the main project.
Yeah welcome my modular101 haha.
OK I will create RetryView for common UI in BaseUI .
Configure your Swift Package
OK I after create and changeName SwiftUIView to RetryView you will get a lot of errors
You can fix follow Xcode guide
OK then if your UI preview is error to display you should select target build name your package (my case is BaseUI) and click refresh like below image.
Modify RetryView (my case demo)
Platform-specific
If you only aim to support a subset of the platform and don’t want to put conditional blocks everywhere, you can specify the supported platform in Package.swift
file under the platforms
key. This will make our Swift package become a platform-specific package.
I make the package only support iOS 13 and forward by specifying platforms: [.iOS(.v13)]
.
You can make your package either platform-independent or platform-specific. The choice is totally up to you.
Add dependency to the new Swift Package
To add a new Swift package dependency:
- Select your project in the Project navigator, then select your app target and navigate to its General pane.
2. Click the + button in the “Frameworks, Libraries, and Embedded Content” section
Then Select the local package’s library product, and add it as a dependency.
Add is done we will see like this
Add import declarative.
Then you need to add the import directive just like other modules.
Change access levels
If you do follow me you will see error when you use RetryView because in view that not declare access in public
Our code still failed at this point Then Fix it
Demo Time
Use RetryView in your project
Yeah you can use this then if your result play preview is blank view no worry about it.
May be problem SwiftUI preview can’t preview cross module in case of UI .
You can run your simulator for test.
Conclusion
This article I write for practice start modular style and I hope article helpful for everyone want to know create modular style and create swift package
And we can start to see the benefit of modular programming with just a simple app like this. Our BaseUI
becomes self-contain; we can focus only on the UI element in that module, and business logic from the main app can't leak into our UI.
Thank you for read.
link Demo Github : https://github.com/JARNBOY/ModularSPMDemo