I am making an attempt to create an extension for the UIView serving to to activate the constraints simply.
Utilizing the brand new Swift 5.9 function Parameter Pack, I’ve the worth of the constraint that confirms to ExpressibleByIntegerLiteral
and the energetic
perform duties parameter pack of UIViewConstraint
.
protocol UIViewConstraint {
associatedtype Anchor: AnyObject
var anchor: NSLayoutAnchor<Anchor>? { get }
var attribute: NSLayoutConstraint.Attribute { get }
var worth: UIView.ConstraintValue { get }
}
extension UIView {
struct Constraint<Anchor: AnyObject>: UIViewConstraint {
var anchor: NSLayoutAnchor<Anchor>?
var attribute: NSLayoutConstraint.Attribute
var worth: UIView.ConstraintValue
}
}
extension UIViewConstraint the place Anchor == NSLayoutYAxisAnchor {
static func prime(_ worth: UIView.ConstraintValue, to anchor: NSLayoutYAxisAnchor? = nil) -> UIView.Constraint<NSLayoutYAxisAnchor> {
UIView.Constraint(anchor: anchor, attribute: .prime, worth: worth)
}
static func backside(_ worth: UIView.ConstraintValue, to anchor: NSLayoutYAxisAnchor? = nil) -> UIView.Constraint<NSLayoutYAxisAnchor> {
UIView.Constraint(anchor: anchor, attribute: .backside, worth: worth)
}
}
extension UIView {
struct ConstraintValue {
var fixed: CGFloat
}
}
extension UIView.ConstraintValue: ExpressibleByIntegerLiteral {
init(integerLiteral worth: Int) {
self.init(fixed: CGFloat(worth))
}
}
extension UIView {
func energetic<every Anchor>(_ constraint: repeat UIView.Constraint<every Anchor>) {
(repeat _active(every constraint))
}
func active2<every Constraint: UIViewConstraint>(_ constraint: repeat every Constraint) {
(repeat _active(every constraint))
}
non-public func _active<T: UIViewConstraint>(_ anchor: T) {
//
}
}
Once I tried to cross an int literal to the generic capabilities energetic(_:)
or active2(_:)
I acquired an error ‘Can not convert worth of sort ‘Int’ to anticipated argument sort ‘UIView.ConstraintValue’‘.
However creating an object from ‘UIView.Constraint‘ immediately works tremendous.
let superView = UIView()
let view = UIView()
superView.addSubview(view)
view.energetic(
.prime(10), // ❌ Can not convert worth of sort 'Int' to anticipated argument sort 'UIView.ConstraintValue'
.backside(20) // ❌ Can not convert worth of sort 'Int' to anticipated argument sort 'UIView.ConstraintValue'
)
view.active2(
.prime(10), // ❌ Can not convert worth of sort 'Int' to anticipated argument sort 'UIView.ConstraintValue'
.backside(20) // ❌ Can not convert worth of sort 'Int' to anticipated argument sort 'UIView.ConstraintValue'
)
let prime: UIView.Constraint<NSLayoutYAxisAnchor> = .prime(10) // ✅
let backside: UIView.Constraint<NSLayoutYAxisAnchor> = .backside(20) // ✅
view.energetic(prime, backside) // ✅
view.active2(prime, backside) // ✅