in Chapter 13, the extension code works well after I imported to my project.
It would be great if there is explanation of the code in the book.
Those code are beyond a beginner level. Thank you.
Hi, I am reading “iOS Apprentice Eighth Edition_ Beginning iOS Development with Swift and UIKit”. The Chapter 13, import 3 extension of Binding, ForEach, and IndexedCollection, because the original ForEach cannot do a binding parameter. " The problem is that
you can only create a binding to a @State or @Binding variable, and the
checklistItem inside ForEach’s braces is neither." So create 3 extensions to walk around the issue. Well, I am new to swift. I guess I may understand below syntax in later chapter or next advanced book which may explain this code.
public extension Binding where Value: CaseIterable & Equatable {
var caseIndex: Binding<Value.AllCases.Index> {
Binding<Value.AllCases.Index>(
get: { Value.allCases.firstIndex(of: self.wrappedValue)! },
set: { self.wrappedValue = Value.allCases[$0] }
)
}
}
public extension ForEach where Content: View {
init<Base: RandomAccessCollection>(
_ base: Base,
@ViewBuilder content: @escaping (Data.Element) → Content
)
where
Data == IndexedCollection,
Base.Element: Identifiable,
ID == Base.Element.ID
{
self.init(IndexedCollection(base: base), id: .element.id, content: content)
}
init<Base: RandomAccessCollection>(
_ base: Base,
@ViewBuilder content: @escaping (Data.Index) → Content
)
where
Data == IndexedCollection,
Base.Element: Identifiable,
ID == Base.Element.ID
{
self.init(base) { index, _ in content(index) }
}
}
public struct IndexedCollection<Base: RandomAccessCollection>: RandomAccessCollection {
let base: Base
}
//MARK: RandomAccessCollection
public extension IndexedCollection {
typealias Index = Base.Index
typealias Element = (index: Index, element: Base.Element)
var startIndex: Index { base.startIndex }
var endIndex: Index { base.endIndex }
func index(after i: Index) → Index {
base.index(after: i)
}
func index(before i: Index) → Index {
base.index(before: i)
}
func index(_ i: Index, offsetBy distance: Int) → Index {
base.index(i, offsetBy: distance)
}
subscript(position: Index) → Element {
(index: position, element: base[position])
}
}Preformatted text