{ $0 * $0 >= x } } func sqrt(x: Int) -> Int { var l = 0 var r = x while l <= r { let m = (l + r) / 2 if m * m >= x { r = m - 1 } else { l = m + 1 } } return l } Scenario Compute ceiling of √𝒙 with Binary Search (Find the smallest integer ≥ √𝒙) √𝟏 = 𝟏 √𝟒 = 𝟐 √𝟏𝟎 ≈ 𝟒
View { Text(message.text) .visualEffect { [pulse] content, _ in content .blur(radius: pulse ? 2 : 0) } } Capture List Given an array of scores, count how many scores are above the average Prevent Data Races Prevent Retain Cycle [pulse] self.onEvent = { [weak self] in self?.navigationController?.popViewController(animated: true) } [weak self]
View { let pulse = pulse Text(message.text) .visualEffect { content, _ in content .blur(radius: pulse ? 2 : 0) } } Capture List Given an array of scores, count how many scores are above the average Prevent Data Races Prevent Retain Cycle let pulse = pulse weak var weakSelf = self self.onEvent = { weakSelf?.navigationController?.popViewController(animated: true) } weak var weakSelf = self
scores.filter({ $0 >= 60 }).max() else { return nil } return 100 - maxPassingScore } Scenario Calculate the difference between the highest passing score (≥ 60) and 100 If no score is passing, return nil
>= 60 } .max() .map { (maxPassingScore: Int) -> Int in 100 - maxPassingScore } } Optional.map(_:) Calculate the difference between the highest passing score (≥ 60) and 100 If no score is passing, return nil .map { (maxPassingScore: Int) -> Int in 100 - maxPassingScore }
integer target Return indices of the two numbers such that they add up to target func twoSum(_ nums: [Int], _ target: Int) -> [Int] { nums .indices .combinations(ofCount: 2) .first { nums[$0[0]] + nums[$0[1]] == target } ?? [] } nums target target
integer target Return indices of the two numbers such that they add up to target func twoSum(_ nums: [Int], _ target: Int) -> [Int] { nums .indices .firstNonNil { [group = nums.indices.grouped { nums[$0] }] i in group[target - nums[i], default: []] .first { $0 != i } .map { j in [i, j] } } ?? [] } nums target target