본 시리즈는 Stanford cs193p 강의(https://cs193p.sites.stanford.edu)를 듣고 필요한 내용을 정리한 것입니다.
이번 강의의 목표: 카드뷰를 격자형태(Grid)로 만들기
일단 Grid 를 먼저 선언하고 시작하자. viewModel.cards 를 인풋으로 받으면, 격자형태로 CardView를 그려주는 요소이다.
var body: some View {
Grid(items: viewModel.cards) { element in
CardView(card: element).onTapGesture {
self.viewModel.choose(card: element)
}.padding()
}.foregroundColor(Color.orange)
}
Grid.swift와 GridLayout.swift 파일을 준비하자. GridLayout.swift는 강의에서 보일러플레이트 코드를 제공한다.
import SwiftUI
// 두개의 argument를 받는 Grid. 하나는 cards 배열이고, 다른 하나는 ForEach와 비슷한 기능을 해줄 함수.
struct Grid<Item, ItemView>: View where Item: Identifiable, ItemView: View {
var items: [Item]
var viewForItem: (Item) -> ItemView
init(items: [Item], viewForItem: @escaping (Item) -> ItemView) {
self.items = items
self.viewForItem = viewForItem
}
var body: some View {
GeometryReader{ geometry in
self.body(for: GridLayout(itemCount: self.items.count, in: geometry.size))
}
}
func body(for layout: GridLayout) -> some View {
ForEach(items) { item in
self.body(for: item, in: layout)
}
}
func body(for item: Item, in layout: GridLayout) -> some View{
let index = items.firstIndex(matching: item)
return viewForItem(item).frame(width: layout.itemSize.width, height: layout.itemSize.height)
.position(layout.location(ofItemAt: index))
}
}
Item과 ItemView 라는 제네릭 두개를 인풋으로 받는 View 구조체이다. 이때 Item은 Identifiable 프로토콜을 따르고, ItemView는 View 프로토콜을 따른다(where 문법 사용).
.firstIndex(matching:)은 Array 에 extension 을 이용하여 추가한 함수다.
extension Array where Element: Identifiable {
func firstIndex(matching: Element) -> Int {
for index in 0..<self.count {
if self[index].id == matching.id {
return index
}
}
return 0 // TODO: bogus
}
}
import SwiftUI
struct GridLayout {
var size: CGSize
var rowCount: Int = 0
var columnCount: Int = 0
init(itemCount: Int, nearAspectRatio desiredAspectRatio: Double = 1, in size: CGSize) {
self.size = size
// if our size is zero width or height or the itemCount is not > 0
// then we have no work to do (because our rowCount & columnCount will be zero)
guard size.width != 0, size.height != 0, itemCount > 0 else { return }
// find the bestLayout
// i.e., one which results in cells whose aspectRatio
// has the smallestVariance from desiredAspectRatio
// not necessarily most optimal code to do this, but easy to follow (hopefully)
var bestLayout: (rowCount: Int, columnCount: Int) = (1, itemCount)
var smallestVariance: Double?
let sizeAspectRatio = abs(Double(size.width/size.height))
for rows in 1...itemCount {
let columns = (itemCount / rows) + (itemCount % rows > 0 ? 1 : 0)
if (rows - 1) * columns < itemCount {
let itemAspectRatio = sizeAspectRatio * (Double(rows)/Double(columns))
let variance = abs(itemAspectRatio - desiredAspectRatio)
if smallestVariance == nil || variance < smallestVariance! {
smallestVariance = variance
bestLayout = (rowCount: rows, columnCount: columns)
}
}
}
rowCount = bestLayout.rowCount
columnCount = bestLayout.columnCount
}
var itemSize: CGSize {
if rowCount == 0 || columnCount == 0 {
return CGSize.zero
} else {
return CGSize(
width: size.width / CGFloat(columnCount),
height: size.height / CGFloat(rowCount)
)
}
}
func location(ofItemAt index: Int) -> CGPoint {
if rowCount == 0 || columnCount == 0 {
return CGPoint.zero
} else {
return CGPoint(
x: (CGFloat(index % columnCount) + 0.5) * itemSize.width,
y: (CGFloat(index / columnCount) + 0.5) * itemSize.height
)
}
}
}
enum Optional<T> {
case none
case some(T)
}
let hello: String? = ...
print(hello!)
switch hello {
case .none: // raise an exception. program crash
case .some(let data): print(data)
}
느낌표(!)를 붙여 강제 언래핑 했는데 nil이면 프로그램이 죽는다.
if let safehello = hello {
print(safehello)
} else {
// do something for error handling
}
switch hello {
case .none: { // do something }
case .some(let data): print(data)
}
hello 변수의 값이 nil 이 아닐때만 if 문이 트루가 돼서 print 가 실행된다. 안전하게 옵셔널을 처리하는 방법.
옵셔널의 디폴트 값은 기본적으로 nil이다. 하지만 nil-coalescing operator(??)를 이용하면 다른 디폴트 값을 설정할 수 있다.
let x: String? = ...
let y = x ?? "foo"
switch x {
case .none: y = "foo"
case .some(let data): y = data
}
none 케이스에서 nil 값 대신 "foo"라는 값이 할당된다.