The document discusses Swift features related to variables, functions, and protocols. It provides examples of using var and inout keywords to pass variables by reference into functions. It also demonstrates defining generic functions that accept parameters and return functions.
61. func freeFall(context: Context)
-> (time: Double) -> Double {
return { time in
-1 / 2 * time * time *
context.gravitationalAcceleration
}
}
62. // コンテキストを固定し、その環境を前提に動く関数を定義
let earth = Context(identifier: "Earth",
gravitationalAcceleration: 9.80665)
let freeFallOnEarth: (time: Double) -> Double
= freeFall(context: earth)
// 汎用関数でスマートに捌く
let timeInterval
= stride(from: 0.0, through: 100.0, by: 1.0)
let locations = timeInterval.map(freeFallOnEarth)
63. func function(object: Object)(multiple: Int) -> Int {
let value = object.value
return value * multiple
}
do {
let f = function(Object(100))
print(f(multiple: 5))
}
64. func function(object:Object) -> (multiple:Int) -> Int {
let value = object.value
return { multiple in value * multiple }
}
do {
let f = function(Object(100))
print(f(multiple: 5))
}
65.
66.
67. func function(var initial value: Int, count: Int) -> Int {
(1 ..< count).forEach { _ in
value += value
}
return value
}
68. func function(var initial value: Int, count: Int) -> Int {
(1 ..< count).forEach { _ in
value += value
}
return value
}
var value = 10
let answer = function(initial: value, count: 5)
69. func function(initial value: inout Int, count: Int) {
(1 ..< count).forEach { _ in
value += value
}
}
var value = 10
function(initial: &value, count: 5)
70. func function(var initial value: Int, count: Int) -> Int {
// 即座に value に変更を仕掛けていける
(1 ..< count).forEach { _ in
value += value
}
return value
}
71. func function(initial value: Int, count: Int) -> Int {
// 編集できるように新しい可変値変数で受け直す
var value = value
(1 ..< count).forEach { _ in
value += value
}
return value
}
72. func function(initial value: Int, count: Int) -> Int {
return (1 ..< count).reduce(value) { value, _ in
value + value
}
}
73. func function(let initial value: Int, count: Int) -> Int {
return (1 ..< count).reduce(value) { value, _ in
value + value
}
}
74. // if var 構文で使用可能
if var value = optionalValue { … }
// while 構文で使用可能
while var value = iterator.next() { … }
// for 構文で使用可能
for var value in values { … }
// switch 構文で使用可能
switch optionalValue {
case .some(var value): …
case .none: …
}
75. // guard var 構文が使用可能
guard var value = optionalValue else {
fatalError()
}
// これ以降で可変値変数 value が使える
value += 200