/
README.md
5111 lines (3748 loc) · 156 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# A Flock of Swifts
We are a group of people excited by the Swift language. We meet each Saturday morning to share and discuss Swift-related topics.
All people and all skill levels are welcome to join.
- **RSVP**: https://www.meetup.com/A-Flock-of-Swifts/
## 2022.12.31
### Problems with Button Layout
Rainer is having trouble with getting button layout to work like he wants.
### Performance
On rotation Ed was hitting a layout performance issue. The suggestion was to try Instruments to see where the computations were going.
### AFOS-Process
Implement a command line tool to process the AFOS readme file and reverse the summaries to appear in chronological order.
- Argument Parser is nice
- Used Regex Builder (trouble with ^ anchor matches)
### Implementing cmap
Josh gave a 2022 final treatise on functional thinking with a focus on comap.
Some materials to get started:
- https://www.pointfree.co It is a little pricey, but there is a good holiday discount of 25%.
- https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/ Bartosz Milewski
- http://learnyouahaskell.com
- https://bow-swift.io/docs/
- https://www.objc.io/books/functional-swift/
Josh implemented cmap (contraMap):
```swift
struct Predicate<A> {
let satisfies: (A) -> Bool
func callAsFunction(_ x: A) -> Bool { satisfies(x) }
}
typealias F = Predicate // So it matches the Scala chart
let isEqualToFive = Predicate { $0 == 5 }
let isWordleWord = cmap(\String.count)(isEqualToFive)
print(isWordleWord("Swift")) // true
print(isWordleWord("Kotlin")) // false
func isPoop(_ value: Int) -> Bool {
value.isMultiple(of: 2)
}
func contraMap<A, B, C> (
_ f: @escaping (A) -> C,
transform: @escaping (B) -> A
) -> (B) -> C {
f(transform($0))
}
let isPoopString = contraMap(isPoop, transform: \String.count)
print(isPoopString("Swift")) // false
print(isPoopString("Kotlin")) // true
```
---
## 2022.12.17
### Tables, Geometry and Layout
Rainer showed us his button layout demo. Peter suggested using
```swift
VStack {
LazyVGrid {} // Row 1
LazyVGrid {} // Row 2
LazyVGrid {} // Row 3
:
}
```
Some layout alternatives and tools:
- https://github.com/joshuajhomann/Radial
- https://github.com/joshuajhomann/PopTip-SwiftUI
### Charts
Ed showed an example of charting. He needed to convert some dates to strings to prevent the graphing system from rearranging them. If you want a basic intro to Swift Charts in iOS 16
- https://www.kodeco.com/36025169-swift-charts-tutorial-getting-started
### ChatGPT
Emil showed an example of ChatGPT making a simple TODO list app in SwiftUI. It was pretty basic could then be iterated on.
John showed a counter example where they asked it to generate a biography of their father. It got one thing correct and the rest of it just made up (total BS).
We will probably see more AI tools in IDEs
### SE Pitches and Proposals
- https://forums.swift.org/t/pitch-swift-predicates/62000
- https://forums.swift.org/t/pitch-observation/62051
- https://github.com/apple/swift-evolution/blob/main/proposals/0382-expression-macros.md
- https://github.com/apple/swift-evolution/blob/main/proposals/0381-task-group-discard-results.md
- https://github.com/apple/swift-evolution/blob/main/proposals/0379-opt-in-reflection-metadata.md
Swift Evolution will now approve Vision documents for large multi-proposal features. A link from Bill.
- https://forums.swift.org/c/evolution/18
---
## 2022.12.10
### Swift Foundation Open Source
Peter reports a big announcement on the Swift blog:
https://www.swift.org/blog/future-of-foundation/
- No more C libraries
- More granular libraries
- Unification of implementations
- Open contribution process
### Customizing Toggles
You can customize SwiftUI toggle by making a `ToggleStyle`.
```swift
struct RadioToggleStyle: ToggleStyle {
func makeBody(configuration: Configuration) -> some View {
Button(action: {
configuration.isOn.toggle()
}) {
Image(systemName: configuration.isOn ? "circle.fill" : "circle")
.accessibilityLabel(configuration.isOn ? "On" : "Off")
}
.buttonStyle(.plain)
}
}
```
Make specifying it feel natural:
```swift
extension ToggleStyle where Self == RadioToggleStyle {
static var radio: Self {
.init()
}
}
```
Using it is as easy as:
```swift
Toggle("The Toggle", isOn: $isChecked)
.toggleStyle(.radio)
```
### Functional Programming
Monads delay the result of effects. Just as with `try/throws` and `async/await` you kick the responsibility up the ladder to the caller, essentially delaying the effect of errors/suspensions. Optionals, arrays, publishers, streams can be viewed as just this.
It takes a change in thinking in going from imperative to functional and takes practice. A good way to practice is with the advent of code exercises.
https://adventofcode.com
### Crates and cranes!
Josh took on a solution of the advent of code day five.
https://adventofcode.com/2022/day/5
The problem can be solved as two sub problems.
Create the initial state by:
1. Unfold the string into lines, up to the delimiter
2. trasnform the lines into an array of tuples of (column, characters)
3. reverse the sequence so we start from the bottom
4. fold the tuples into an array of columns, which are each an array of characters
```swift
let columns = sequence(state: scanner) { scanner -> String? in
scanner.scanUpToCharacters(from: .newlines).flatMap { $0 == " 1 2 3 4 5 6 7 8 9" ? nil : $0 }
}
.flatMap { line in
line
.enumerated()
.filter { $1.unicodeScalars.first.map(CharacterSet.uppercaseLetters.contains) ?? false }
.map { value in
(column: (value.offset - 1) / 4, value: value.element)
}
}
.reversed()
.reduce(into: [[Character]](repeating: [], count: 9)) { columns, box in
columns[box.column].append(box.value)
}
```
Second, fold the moves into the initial state and extract the answer form the final state:
1. Unfold the rest of the string into a tuple of (quantity, from, to) by extracting the 3 integers from each line and ignoreing everything else
2. Fold the sequence of moves into the initial state by removing quanity items from the end of the from array and placing them at the end of the to array
3. Pluck out the last character from each column and join them into a String
```swift
scanner.charactersToBeSkipped = .decimalDigits.inverted
return sequence(state: scanner) { scanner -> (quantity: Int, from: Int, to: Int)? in
guard let quantity = scanner.scanInt(),
let from = scanner.scanInt().map({ $0 - 1}),
let to = scanner.scanInt().map({ $0 - 1}) else {
return nil
}
return (quantity: quantity, from: from, to: to)
}
.reduce(into: columns) { columns, move in
let transfer = shouldReverse
? columns[move.from].suffix(move.quantity).reversed()
: columns[move.from].suffix(move.quantity)
columns[move.to].append(contentsOf: transfer)
columns[move.from].removeLast(move.quantity)
}
.map { $0.last.map(String.init(describing:)) ?? " " }
.joined()
```
You can see his solution here:
https://github.com/joshuajhomann/Advent-of-Code-2022/blob/main/Advent.playground/Pages/Day%205.xcplaygroundpage/Contents.swift
---
## 2022.12.03
### Functional Design Patterns
Monads are a functional design pattern with origins in category theory. Monads give us a tool for modelling effects. We went through the basics following some popular online posts including:
- https://mokacoding.com/blog/functor-applicative-monads-in-pictures/
- https://www.hackingwithswift.com/example-code/language/what-is-a-monad
ASIDE: Don't confuse functors with function objects.
```swift
// This is a function object, not a functor.
class ViewModel {
func callAsFunction() {
print("Hello")
}
}
let viewModel = ViewModel()
viewModel() // prints Hello
```
- Functors: implement map
- Applicative: implements lift and apply
- Monad: implements flatMap
Monads are special forms of applicatives. Applicatives are special forms of functors. Optionals, Arrays, Results, Publishers.
#### Functor Examples
```swift
func compute(_ input: Int) -> Int {
input + 42
}
Optional<Int>(nil).map(compute(_:))
[5].map { compute($0) }
```
#### Applicative Example
```swift
extension Optional {
func apply<ReturnType>(_ f: ((Wrapped) -> ReturnType)?) -> ReturnType? {
guard let f else { return nil }
return self.map(f)
}
}
extension Array {
func apply<ReturnType>(_ fs: [(Element) -> ReturnType]) -> [ReturnType] {
var result = [ReturnType]()
result.reserveCapacity(fs.count * self.count)
for f in fs {
for element in self.map(f) {
result.append(element)
}
}
return result
}
}
[3,2,3].apply([compute(_:), compute(_:)])
```
#### The Monadic Laws
1. Left identity - flat mapping a monad with a function is the same as calling that function
2. Right identity - flat mapping a lifted monad is the same as the monad
3. Associativity - chaining operations is the same as nesting operations
(You can find code examples in the Hacking with Swift)
Tim Colson Suggested this reading:
https://stackoverflow.com/questions/28139259/why-do-we-need-monads
### Functional Symmetry
![image](materials/IMG_1363.PNG)
We discussed how functors, applicatives, monads and related constructs can all be constructed as transforms of A's, B's arrows and F's and the fact that `filter`, `compactMap` and `flatMap` have the same shape, which is why `compactMap` was originally the same function as `flatMap` in earlier versions of swift; they are the same function with different choices for the Monads. You can rewrite `filter` in terms of `compactMap` or in terms of `flatMap`
```swift
print((0...10).prefix(10).filter { $0.isMultiple(of: 2)})
print((0...10).prefix(10).compactMap { i -> Int? in i.isMultiple(of: 2) ? i : nil })
print((0...10).prefix(10).flatMap { $0.isMultiple(of: 2) ? [$0] : [] })
```
### Functor as a protocol
We looked at how you can implment a functor as a protcol and the symmetry between the free function `fmap` which lifts a function from `A->B` to a function `FA->FB` and the instance method `map` which takes a `A->B` and returns `FB`. With the implicit self parameter to the instance method it becomes `(A->B), FA -> FB` which is the same as the curried function `(A->B) -> FB -> FA`.
```swift
protocol Functor<A> {
associatedtype A
associatedtype FB: Functor = Self
associatedtype FA: Functor = Self
typealias B = FB.A
static func fmap(_ transform: @escaping (A) -> B) -> (FA) -> FB
func fmap<T>(_ transform: @escaping (A) -> T) -> FB where T == FB.A
}
extension Optional: Functor {
typealias A = Wrapped
static func fmap(_ transform: @escaping (A) -> B) -> (FA) -> FB {
{ fa in
guard let a = fa else { return nil }
return transform(a)
}
}
static func pure(_ value: Wrapped) -> Self {
.some(value)
}
func fmap<B>(_ transform: @escaping (A) -> B) -> B? {
guard let self else { return nil }
return transform(self)
}
}
let v = Optional<Int>.fmap({ $0 * 2 })(5)
let v2 = Optional<Int>.pure(5).fmap { $0 * 2 }
```
### Advent of Code
Josh showed his solution for day one of the (Advent of Code 2022)[https://adventofcode.com] and explained how it makes use of monads:
```swift
let input = Bundle.main.url(forResource: "input", withExtension: "")
.flatMap { try? Data(contentsOf:$0) }
.flatMap { String(data: $0, encoding: .utf8) }!
let total = sequence(state: Scanner(string: input)) { scanner in
scanner.scanUpToString("\n\n").map { subarrayString in
sequence(state: Scanner(string: subarrayString)) { $0.scanInt() }.reduce(0, +)
}
}
.max()!
```
You can find his complete set of solutions for the advent of code [here](https://github.com/joshuajhomann/Advent-of-Code-2022)
### Miscellaneous
- https://arstechnica.com/information-technology/2022/12/apple-slices-its-ai-image-synthesis-times-in-half-with-new-stable-diffusion-fix/
Why no test flight?
- https://www.whynotestflight.com
## 2022.11.27
### Diagrams
Rainer showed how to programatically create flow charts and sequence diagrams with [PlantUML](https://plantuml.com):
```
@startuml BF Flow - State Diagram
title BF Flow in plantUML
hide empty description
note right of Root: This is the starting point
Root --> TermsAndConditions
TermsAndConditions --> UserNameAndEmail
UserNameAndEmail -> Phone
Phone -> UserNameAndEmail
UserNameAndEmail --> IconSelection
IconSelection -> PointsCount
PointsCount --> Root
Root --> Welcome
state Contest {
state Artwork {
}
state Winners {
}
}
Welcome -down-> Contest
Artwork -down-> SpaceBuilder
SpaceBuilder -left-> Profile
Profile -up-> Welcome
Welcome -left-> RunningCount
RunningCount --> YourPoints
YourPoints --> RunningCount
@enduml
```
```
stateDiagram-v2
Root --> Welcome : tap ENTER
Welcome --> Announcements
note right of Announcements : This is the note to the right.
Welcome --> Contest
Contest --> Winners
Contest --> ShareToSocial
Contest --> CreateArtwork : Create_Art
CreateArtwork --> ArtBuilder : auto-open
ArtBuilder --> ShareArt
ShareArt --> CreateArtwork
```
```
digraph mygraph {
// concentrate=true
layout="dot"
node [fontname="Helvetica,Arial,sans-serif"]
edge [fontname="Courier,Arial,sans-serif"]
node [shape=box];
"Root" -> {Welcome, "Terms and conditions"}
"Points Count" -> Root
lc [label="UserName & Email", xlabel="external label on username"]
"Terms and conditions" -> lc
Phone [style=filled, fillcolor="red", constraint=false]
lc -> "Icon Selection"
lc -> Phone [dir=both] [label="edge label"]
"Icon Selection" -> "Points Count" [label="edge label", fontcolor="blue"]
Welcome -> {"RunningCount", "Contest"} [dir=both]
"RunningCount" -> {"Your Points"} [dir=both]
"Your Points" -> Welcome [constraint=false]
Contest -> ArtBuilder -> ArtViewer -> Welcome
Contest [xlabel="label on Contest"]
note [label="root note", shape=note, penwidth=0.2, fillcolor=yellow, style="filled", height=0.001, margin=0.01, fontsize=10]
note -> Root [minlen=0.1, penwidth = 1.0, arrowhead=none, style="dashed", color="grey"]
Contest [shape=Mrecord, label="{Contest|Artwork|Winners}"]
}
```
### Swift Previews
Ed shared how to customize a view for swift previews using an environment variable:
```swift
import SwiftUI
struct TestView: View {
var body: some View {
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
Text("Preview Text")
} else {
Text("Device Text")
}
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
```
### WidgetKit
Josh showed how to create a widget. The code is availble [here.](https://github.com/joshuajhomann/)
![image](https://github.com/joshuajhomann/SpaceStationTracker/blob/main/preview.gif)
---
## 2022.11.19
### Generic RadioGroup in SwiftUI
Josh presented a solution to Ed's question from last week with a goal of meeting the following design criteria:
* Declarative
* Idiomatic
* Expressive
* Consistent
* Extensible
* Reusable
* Composable
The first draft was as follows:
```swift
struct RadioPicker<Item: Identifiable, ItemView: View>: View {
var items: [Item]
@Binding var selection: Item?
@ViewBuilder var content: (Item, Bool) -> ItemView
var body: some View {
ForEach(items) { item in
content(item, item.id == selection?.id).onTapGesture { selection = item }
}
}
}
struct Num: Identifiable {
var value: Int
var id: Int { value }
}
```
Limitations of this version include a lack of consistency with the `List` api, the need for an `Identifiable` wrapper and possible repetative code with the obligator `ViewBuilder`.
The second draft makes the initializers consistent with `List` and drops the identifiable requirement when the user provides a `KeyPath` for the id:
```swift
struct V: View {
@State var selection: Num?
private let numbers = (1...5).map(Num.init(value:))
var body: some View {
VStack {
RadioPicker(items: numbers, selection: $selection) { item, isSelected in
Text("Item: \(item.value)")
.padding()
.background(isSelected ? Color.blue : Color.gray)
.cornerRadius(8)
}
Text(selection.map { "You selected \($0.value)" } ?? "Select an Item")
}
}
}
struct RadioPicker2<Item, SomeHashable: Hashable, ItemView: View>: View {
private var items: [Item]
private var id: KeyPath<Item, SomeHashable>
@Binding private var selection: Item?
private var content: (Item, Bool) -> ItemView
var body: some View {
ForEach(items, id: id) { item in
content(item, item[keyPath: id] == selection?[keyPath: id]).onTapGesture { selection = item }
}
}
init(
_ items: [Item],
id: KeyPath<Item, SomeHashable>,
selection: Binding<Item?>,
@ViewBuilder content: @escaping (Item, Bool) -> ItemView
) {
self.items = items
self.id = id
_selection = selection
self.content = content
}
init(
_ items: [Item],
selection: Binding<Item?>,
@ViewBuilder content: @escaping (Item, Bool) -> ItemView
) where Item: Identifiable, Item.ID == SomeHashable {
self.init(items, id: \.id, selection: selection, content: content)
}
}
struct V_2: View {
@State var fruitSelection: String?
@State var numberSelection: Num?
private let fruit = ["Apple", "Orange", "Pear", "Bannana"]
private let numbers = (1...3).map(Num.init(value:))
var body: some View {
HStack {
RadioPicker2(fruit, id: \.self, selection: $fruitSelection) { fruit, isSelected in
Text(fruit)
.foregroundColor(.white)
.padding()
.background(isSelected ? Color.accentColor : Color.secondary)
.cornerRadius(8)
}
}
Text(fruitSelection.map { "You selected \($0)" } ?? "Select a fruit")
Divider()
RadioPicker2(numbers, selection: $numberSelection) { number, isSelected in
HStack {
Image(systemName: isSelected ? "checkmark.square" : "square")
Text(String(describing: number.value))
}
}
}
}
```
The final version use static member lookup to create a `RadioGroupStyle` that can be injected into the environment, obviating the need for a `ViewBuilder` when the pick item title is representable as a string. It is a available as a [swift package](https://github.com/joshuajhomann/RadioGroup).
![image](https://github.com/joshuajhomann/RadioGroup/raw/main/preview.gif "Preview")
--
## 2022.11.12
### Conferences and Getting Started
At different points during the meeting we talked about conferences and getting started with Swift.
#### New Conferences
- Deep Dish Swift in Chicago https://deepdishswift.com
- NY Swifty https://nyswifty.com
Then there are some online ones:
### SwiftPM Autocomplete
#### https://www.tryswift.co/world/
Frank is giving his Distributed Actors workshop next week.
If you are just getting started and have a CS background Josh and Ed recommend Stanford CS 193P. Also, 100 days of SwiftUI.
#### Getting a Job
Some ideas (in no particular order):
- https://www.builtinla.com
- https://iosdevjobs.com
- https://www.cybercoders.com
### A Radio Button Control
Ed worked on a custom radio button. The code he presented is simple but a little manual. Suggestions from the group (notably Josh) included following the API design of SwiftUI picker. Maybe a topic for next time?
Here's Ed's code:
```swift
import SwiftUI
struct RadioOption {
let title : String
var isOn : Bool
init(_ title: String, _ isOn: Bool) {
self.title = title
self.isOn = isOn
}
}
struct RadioButton: View {
@Binding var option : RadioOption
var tapped : (Bool) -> ()
var body: some View {
HStack {
Image(systemName: option.isOn ? "largecircle.fill.circle" : "circle")
.renderingMode(.original)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 32, height: 32)
Text(option.title)
}
.onTapGesture {
if !option.isOn {
option.isOn = true
tapped(true)
}
}
}
}
struct RadioChoice: View {
@Binding var choice1 : RadioOption
@Binding var choice2 : RadioOption
var changed : () -> ()
init(_ c1: Binding<RadioOption>, _ c2: Binding<RadioOption>, _ changed: @escaping ()->()) {
_choice1 = c1
_choice2 = c2
self.changed = changed
}
var body: some View {
VStack(alignment: .leading, spacing: 20) {
RadioButton(option: $choice1) { _ in choice2.isOn = false; changed() }
RadioButton(option: $choice2) { _ in choice1.isOn = false; changed() }
}
}
}
struct RadioTest: View {
@State private var one = RadioOption("One", false)
@State private var two = RadioOption("Two", false)
@State private var text = "Select"
var body: some View {
VStack(alignment: .leading) {
Text(text)
RadioChoice($one, $two) {
text = one.isOn ? "One" : "Two"
}
}
}
}
struct RadioButton_Previews: PreviewProvider {
static var previews: some View {
RadioTest()
}
}
```
### Decoding an Array of Failable elements
Josh presented a technique for robustly decoding types that might have unexpected JSON in them. (Instead of flatMap of optionals return Result and then split into an array of values and failures.)
```swift
let json =
"""
[
{ "name": "a", "value": 1 },
{ "name": "b", "value": "2" },
{ "name": "c", "value": null },
{ "name": "d" }
]
""".data(using: .utf8)!
extension Result: Decodable where Success: Decodable, Failure == Error {
public init(from decoder: Decoder) throws {
self = Self { try .init(from: decoder) }
}
}
struct FallibleArray<Element: Decodable>: Decodable {
var values: [Element] = []
var failures: [String] = []
init(from decoder: Decoder) throws {
let results = try [Result<Element, Error>](from: decoder)
values.reserveCapacity(results.count)
for result in results {
switch result {
case let .success(value): values.append(value)
case let .failure(error): failures.append(Self.description(for: error))
}
}
}
private static func description(for error: Error) -> String {
switch error {
case let decodingError as DecodingError:
switch decodingError {
case let .typeMismatch(_, context),
let .keyNotFound(_, context),
let .valueNotFound(_, context): return "\(context.codingPath[0].stringValue): \(context.debugDescription)"
case .dataCorrupted: return String(reflecting: error)
}
default: return String(reflecting: error)
}
}
}
struct Example: Codable {
var name: String
var value: Int
}
let decoded = try! JSONDecoder().decode(FallibleArray<Example>.self, from: json)
print(decoded.values.map(\.name))
print(decoded.failures.joined(separator: "\n"))
```
### ParallelMap in the ISS example project
Josh continued his epic ISS example. He showed how a naive version of parallelMap doesn't actually run in parallel and suffers from problems that it can't be cancelled. To do this he leverages taskGroup and guarantees result order (same as input) using a lookup table.
```swift
extension Sequence {
func parallelMap<Transformed>(transform: @escaping (Element) async throws -> Transformed) async throws -> [Transformed] {
var lookup = [Int: Transformed]()
let count = (self as? any Collection)?.count
if let count {
lookup.reserveCapacity(count)
}
_ = try await withThrowingTaskGroup(of: (Int, Transformed).self) { group in
for (index, element) in self.enumerated() {
group.addTask {
(index, try await transform(element))
}
}
for try await item in group {
lookup[item.0] = item.1
}
}
var transformed = [Transformed]()
if let count {
transformed.reserveCapacity(count)
}
return (0..<lookup.count).reduce(into: transformed) { accumulated, next in
accumulated.append(lookup[next]!)
}
}
}
```
This can then be put into the ISS project to reverse geolocate space station positions.
---
## 2022.11.05
### Equatable
Allen King making progress in his app on equatable found this article useful: https://jayeshkawli.ghost.io/using-equatable/
### Mastodon Viewer
Carlyn is working on a Mastodon viewer:
https://github.com/carlynorama/ActivityPubExplorer
### Watch Gestures in the Background
How can you make a gesture always available in the background. This may be impossible (by public API and Apple app store rules). Josh suggested checking out the following:
https://developer.apple.com/documentation/watchkit/background_execution
### DocC Demo
Ray gave a demostration of creating project documentation. There is a full (free) Kodeco tutorial that you can find here:
https://www.kodeco.com/34919511-docc-tutorial-for-swift-getting-started
In Ray's demo he created a "Flashcard" demo that he will be using in the coming weeks to demostrate things.
Here is a list of things you can doument:
https://developer.apple.com/documentation/xcode/writing-symbol-documentation-in-your-source-files
How the parser works:
https://github.com/apple/swift/blob/main/docs/DocumentationComments.md
### ISS App
Josh continued his ISS demo app. He showed how to hookup the endpoint and elegantly show positions on the map that can be tapped for more details with a very small amount of code. Next week he will explore reverse geocoding and async task groups in more detail.
#### Undefined behavior
This undefined behavior warning in Xcode 14 is a false positive:
https://www.donnywals.com/xcode-14-publishing-changes-from-within-view-updates-is-not-allowed-this-will-cause-undefined-behavior/
#### Concurrent forEach
We will discuss some of the gotchas here next week.
https://www.swiftbysundell.com/articles/async-and-concurrent-forEach-and-map/
---
## 2022.10.29
### Kodeko
It started of as Ray Wenderlich's personal blog and evolved into a major mobile development website with hundreds of contributed. Ray had been looking to rename it for years and that time is finally now. Read about the whole story here:
- https://www.kodeco.com/36641071-introducing-kodeco-the-new-raywenderlich-com
### Bridging between Combine and AsyncStream
A quick cut might look like this:
```swift
import SwiftUI
import PlaygroundSupport
import Combine
let publisher = CurrentValueSubject<Int, Error>(1)
var subscription: AnyCancellable? = nil
let stream = AsyncThrowingStream<Int, Error> { continuation in
subscription = publisher.sink(receiveCompletion: { completion in
switch completion {
case .finished: continuation.finish()
case let .failure(error): continuation.finish(throwing: error)
}
}, receiveValue: { value in
continuation.yield(with: .success(value))
})
}
```
Carlyn brought up the fact that you might want to handle cancellation:
```swift
continuation.onTermination = { _ in
streamTask.cancel()
print("StreamTask Canceled")
}
```
She has some experiments that she shared here:
- https://github.com/carlynorama/StreamPublisherTests
### Hosting a Website
- Github pages
- S3 bucket - more complicated but more options
- Franklin suggested https://www.nearlyfreespeech.net
### Building Documentation with DocC
Specific question about including images in documentation.
- https://www.swift.org/blog/swift-docc/
- https://developer.apple.com/documentation/xcode/slothcreator_building_docc_documentation_in_xcode
- https://developer.apple.com/documentation/docc/image
- https://blog.swiftpackageindex.com/posts/auto-generating-auto-hosting-and-auto-updating-docc-documentation/
### Systems Design
A recommendation from Felipe C:
https://www.youtube.com/playlist?list=PLaMN-JyH50OYAfxJEpiQTYTD-gxTf7x9d
If you are really want to take interviewing seriously (Josh) it might be worth the cost:
https://interviewing.io
### Software Engineering
Bjarne Stroustrup talks about C++ and software engineering
https://www.youtube.com/watch?v=2BuJjaGuInI&ab_channel=CppCon
### Continue work on ISS app
- Finish the model (Using @dynamicMemberLookup and Keypaths to add properties to the existing model)
- Start looking at the service to get locations
- Using URLComponents to create a URL
- Next week to do multiple requests to get named locations
Homework (study this):
https://forums.swift.org/t/should-task-groups-inherit-actor/57547
### Hint:
![Table of Inheritence](/materials/task-inheritance.png)
---
## 2022.10.22
### Top security vulnerabilities
* We discussed [this list](https://www.youtube.com/watch?v=ELeZAKCN4tY&ab_channel=CppCon) of security vulnerablities from [this video](https://cwe.mitre.org/top25/archive/2022/2022_cwe_top25.html) and how Swift makes many of these errors impossible without opting into unsafe code.
### Functional programming
* We discussed the Donald Knuth story from [this video](https://www.youtube.com/watch?v=M5HuOZ4sgJE&t=2129s&ab_channel=CppCon) and [this illustrated guide](https://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html) to category theory.
* We mob programmed this solution to the Knuth problem:
```swift
text
.lowercased()
.components(separatedBy: .lowercaseLetters.union(.init(charactersIn: "'")).inverted)
.filter { !$0.isEmpty }
.reduce(into: [String: Int]()) { dictionary, word in
dictionary[word, default: 0] += 1
}
.sorted { $0.value > $1.value }
.prefix(20)
.forEach { print($0) }
```
* We discussed use of `partition` vs `sort`:
```swift
let url = Bundle.main.url(forResource: "declaration", withExtension: "txt")