1. Source of ideas
When I was studying custom operators, I looked at the reloaded operators again. I found it very interesting and I just wrapped a few of them.
2. Basic type String as an example
Overload multiplication operator
Splice a string together n times;
let c = "abc"*3; print("c: \(c)");//c: abcabcabc
Source code implementation:
public extension String{ static func * (lhs: String, rhs: Int) -> String { return String(repeating: lhs, count: rhs); } }
3. Object type UIEdgeInsets as an example
The overload addition operator will
Sum the top, left, bottom, right attributes one by one;
let edg1 = UIEdgeInsets(top: 1, left: 2, bottom: 3, right: 4); let edg2 = UIEdgeInsets(top: 4, left: 3, bottom: 2, right: 1); let e = edg1 + edg2; print("edg1: \(edg1)");//edg1: UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0) print("edg2: \(edg2)");//edg2: UIEdgeInsets(top: 4.0, left: 3.0, bottom: 2.0, right: 1.0) print("e: \(e)");//e: UIEdgeInsets(top: 5.0, left: 5.0, bottom: 5.0, right: 5.0)
Source code implementation:
public extension UIEdgeInsets{ static func + (lhs: UIEdgeInsets, rhs: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsets( + , + , + , + ); } }
4. Summary
1. The overloaded operator can simplify cumbersome operations and encapsulate complex operations, which is a qualitative reconstruction method;
2. The core of programming is creativity. The stronger your ability to create various tool functions, the easier it is to work, and vice versa.
The above is the detailed analysis of the Swift refactoring reload operator example. For more information about Swift refactoring reload operators, please pay attention to my other related articles!