Day 82 - 100 Days of Swift
Consolidation IX
Day 82 is a consolidation day where you review projects 22 through 24. After reviewing some of the key points from those projects, including using CLLocationManager
, UIBezierPath
and extension
, he challenges you to write some extensions of your own. He challenges you to write an extension on UIView
that animates a view down to 0.0001
over a given duration. He challenges you to write an extension on Int
that will take a closure and run it as many times as the Int
. And he challenges you to write an extension on Array
that lets you remove a given item from it.
For the first one I just added a function that takes a duration and a completion closure and animates the view out over that duration:
1
2
3
4
5
6
7
8
9
10
11
12
13
typealias EmptyClosure = () -> Void
extension UIView {
func bounceOut(duration: TimeInterval, completion: ((Bool) -> Void)?) {
let animations: EmptyClosure = {
self.transform = CGAffineTransform.identity.scaledBy(x: 0.0001, y: 0.0001)
}
UIView.animate(withDuration: duration,
delay: 0,
animations: animations,
completion: completion)
}
}
For the second one, I just used forEach
to run the given closure as many times as the Int
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension Int {
func times(closure: EmptyClosure) {
(0..<self.magnitude).forEach { _ in
closure()
}
}
}
let str = "Hello"
3.times { print(str) }
// Prints:
// "Hello"
// "Hello"
// "Hello"
For the third one, I constrained the Element
to be Equatable
and then used the array’s firstIndex(of:)
method to find and remove the element:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
extension Array where Element: Equatable {
@discardableResult
mutating func remove(_ item: Element) -> Element? {
guard let index = firstIndex(of: item) else {
return nil
}
return self.remove(at: index)
}
}
var arr = [1, 2, 3, 4 , 5, 1]
print(arr) // prints [1, 2, 3, 4, 5, 1]
arr.remove(1)
print(arr) // prints [2, 3, 4, 5, 1]
And that’s it for today. Another short and sweet one in the bag!
You can find my version of this playground at the end of day 82 on Github here.