Swift: slow build times when changing struct code - swift

tl;dr
Applying a code change to a commonly used struct causes very slow build times. Can this be avoided?
I have a rather large Swift project (Xcode 9.2) where I use a struct to hold all styling information (colors, spacings, etc.) used by in the app, something like:
struct Style {
var iconColor: UIColor = .darkGray
var lightTextColor: UIColor = .gray
// ... and many more properties ...
static var defaultStyle: Style {
return Style()
}
static var fancyStyle: Style {
var style = Style()
// ... override style props for more fancyness ...
return style
}
}
Every view controller (there are about 30 VCs in the project, all created in code -- no storyboards used) has a Style instance and uses it when rendering its UI:
class MyViewController: UIViewController {
var style = Style.defaultStyle // can be overridden by creator of the VC
override func viewDidLoad() {
super.viewDidLoad()
myLabel.textColor = style.lightTextColor
}
}
This works pretty nicely and allows to change settings in one place only, without polluting the namespace with global constants.
However, I noticed that when changing a property's default value inside the struct the compile time rises dramatically, Xcode basically performs a full rebuild. E.g. changing the above definition of Style.lightTextColor to var lightTextColor: UIColor = .green leads to a build time comparable to a full rebuild of the project. If, however, I change the value directly where it is used; e.g. in the view controller: myLabel.textColor = .green, the project builds very quickly.
Is there a solution for this, preferably by configuring the compiler to do ... less work in this case?

Related

form of initialisation swift

I have seen the following form of initialisation being used in some projects that I have worked on:

class MyClass: UIViewController {
private let myView: MyView!
func initMyView() {
let tempView = MyView()
tempView.someIntProperty = 5
myView = tempView
}
}
I wanted to know if there’s any particular advantage of using such type of initialisation? The only benefit I can see is readability and protecting my class property from mutation. The copy made is a shallow copy so performance isn’t an issue either. Is there any other benefit to using such a way of initialisation?

Overriding UIStackView background color variable

I was shocked to learn that ability to set a background color to a UIStackView come only starting from iOS14. In the older versions such attempts are just ignored.
I have to support older versions as well, so I wrote this code to fix the issue:
public extension UIStackView {
private var helperSubview: UIView {
subviews.first(where: { $0.id == "helperSubview" }) ?? {
let hsv = UIView()
hsv.id = "helperSubview"
insertSubview(hsv, at: 0)
hsv.fillSuperview()
return hsv
}()
}
override var backgroundColor: UIColor? {
didSet {
if #available(iOS 14.0, *) {
return
} else {
helperSubview.backgroundColor = backgroundColor
}
}
}
}
The code works just fine.
But there is one strange moment: in iOS14 didSet doesn't fire at all (like we can even don't check #availability). That suits me, this behaviour doesn't cause any problems. But I don't understand why does it behave like that?
You can't use extension to override a class property. You need to subclass UIStackView if you would like to override any property or method.
From the docs:
Extensions can add new functionality to a type, but they can’t override existing functionality

Inject ViewModifier to SwiftUI View

Current Situtation
I work on an iOS SDK containing several UIViewControllers that can be customized through a delegate function passing a String as the identifier and getting a customized CALayer. With that, the host application can customize how the SDK looks.
This is an example:
extension ViewController: NINChatSessionDelegate {
func ninchat(_ session: NINChatSession, overrideLayer assetKey: CALayerConstant) -> CALayer? {
switch assetKey {
case .ninchatPrimaryButton:
let layer = CALayer()
layer.backgroundColor = UIColor.gray.cgColor
layer.masksToBounds = true
layer.cornerRadius = 20.0
return layer
default:
return nil
}
}
Problem
Nowadays, I'm trying to migrate the code to SwiftUI and Combine. But I cannot find a way to offer host applications to inject their own attributes. As far as I have understood, a ViewModifier struct is used to apply custom attributes to one or multiple View(s) in SwiftUI. However, I could not yet find a way to inject them to the SDK because a ViewModifier protocol has Self or associated type requirements
I appreciate any helps and guides.

SWIFT best practice to share variable across view controllers and inside class functions

I guess I have traced down the issue of the error Instance member 'txtProblem' cannot be used on type 'TextProblemViewController', however, I wonder what is the best practice on how to deal with the underlying issue.
I have a global data structure TextProblems which I use to fetch JSON data. This data is used by multiple view controllers. That is why I declared it as a global variable
var problems:TextProblems!
class TextProblemViewController: UIViewController {
Now I wanted to break my viewDidLoad() apart and moved some code to a separate function, thus
override func viewDidLoad() {
super.viewDidLoad()
do {
problems = try readJsonProblem()
} catch {
print(error.localizedDescription)
}
txtProblem.text = fillParamters(textRaw: problems.textProblem[i].problemStmnt.problemText, parameters: problems.textProblem[i].problemStmnt.problemPrmtr.map {$0.param})
became
let ProblemStmntView: UIView = {
let view = UIView()
view.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.backgroundColor = UIColor.white
txtProblem.text = fillParamters(textRaw: problems.textProblem[i].problemStmnt.problemText, parameters: problems.textProblem[i].problemStmnt.problemPrmtr.map {$0.param})
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
do {
problems = try readJsonProblem()
} catch {
print(error.localizedDescription)
}
view.addSubview(ProblemStmntView)
This results in the above error message at the line txtProblem.text = fillParameters, where txtProblem us an IBOutlet of a label
I have seen 3 resolutions and imagine a 3rd one - and I guess there are more:
declare the variable as static (but this does not work outside a class when declaring the global variable
make the variable lazy, however, I think I cannot declare an IBOutlet as lazy
pass the data from viewDidLoad to my closure (the example showed passing it to a function as a solution), however, not sure how to pass the data to the initialization closure
declare the global variable as static within the structure
So my question is, what do you assume to be best practice when sharing data not initialized before run time across view controllers and class functions? Would you declare a global variable or somehow pass along the data between view controllers, functions (and initialization closures???)?

Xcode 9: Using named colors with IBDesignable and IBInspectable results in Interface Builder error, but compiles without issue

I use UIColor.named("myColor") throughout my app since Xcode 9 came out. While having a shot at a custom implementation of UITextField as an IBDesignable class, I kept getting the following error:
error: IB Designables: Failed to render and update auto layout status
for ViewController (): The agent crashed
Furthermore, my class has several IBInspectable properties, including of type UIColor, but in the Interface Builder dropdown for these properties I could only select the standard colors, my named colors would not show up as they do for standard class properties.
With that latter issue as a clue for the first one, the unsatisfactory and temporary solution has been to not use named colors in my IBDesignable class. Or alternatively, not use IBDesignable.
This is probably a bug, but I'm wondering if other people out there have experienced this issue, and if there are any fixes they've come up with.
[As of Xcode 9.2] This is an unfortunate workaround, but for now I'm using IB-specific stand-in colors. It's not perfect, but we can at least see something while designing in Interface Builder.
#IBDesignable
class MyView: UIView {
#IBInspectable
var addCoolSubview: Bool = false {
didSet {
if self.addCoolSubview {
let coolView = CoolView() // Some custom view with a `coolColor` property.
#if TARGET_INTERFACE_BUILDER
coolView.coolColor = UIColor.blue // An IB-only stand-in color.
#else
coolView.coolColor = UIColor(named: "myCoolBlue") // The run-time color we really want.
#endif
self.addSubview(coolView)
}
}
}
}
Every UIView also has a prepareForInterfaceBuilder() method, which runs only when building for Interface Builder, that could be overridden to similar effect.
#IBDesignable
class MyOtherView: UIView {
var myWarmColor: UIColor? = UIColor(named: "myWarmColor") // Will be `nil` in IB.
// ... view does something with `myWarmColor` that would be visible in IB ...
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
// Set some IB-only stand-in colors here:
self.myWarmColor = UIColor.orange
}
}
With regard to choosing named colors in #IBInspectable properties in Interface Builder, it's only half-broken. As a workaround, you can choose a named color from the Recently Used Colors section, if you can pick it out of the group by sight. When you pick a named color, it will properly display the name, but append (missing) for whatever reason. Just ignore the (missing); it will display properly in IB and at run-time.
One other point of note is that Xcode (as of 9.2) might try to add the named color again to your Storyboard file, so you'll have to check the XML to see if the color is defined there multiple times (color definitions are near the bottom). Or you could just roll with, and eventually Xcode will notice and fix it by itself, blaming the duplicate color definition on SCM.
You just have to specify the bundle.
UIColor(named: "myColor", in: Bundle(for: AppDelegate.self), compatibleWith: nil)!
I found it in another question and works for me on XCode 14.2.