Skip to content

Instantly share code, notes, and snippets.

// `Foo` is an immutable class
final class Foo {
let value: Int
init(_ value: Int) {
self.value = value
}
}
// Adds `mutating func` to `Foo`
protocol Incremental {
// もし if let が存在しなかったら・・・
let a: Int? = Int("...")
if a != nil {
// ここでは a は nil ではないとわかっているけど、
// a の型は Int? なので↓のような計算はできない。
print(a * 2) // コンパイルエラー
// a は nil でないとわかっているのに、↓のように
struct DirectProduct<Left: Sequence, Right: Sequence>: Sequence {
let left: Left
let right: Right
let iteratorType: Iterator.Type
init(_ left: Left, _ right: Right) {
self.left = left
self.right = right
iteratorType = Iterator1.self
}
do { // 一時的な変数 foo のスコープを切る
let foo: Foo
switch bar {
case .a:
foo = ...
case .b:
foo = ...
case .c:
foo = ...
}
protocol Animal {
func foo() -> Int
}
struct Cat: Animal {
var value: Int = 42
func foo() -> Int { return value }
}
func useAnimal(_ animal: Animal) -> Int {
struct Person {
var name: String
var age: Int
}
var a = [
Person(name: "Foo", age: 20),
Person(name: "Bar", age: 30),
]
protocol CatProtocol {
var name: String { get set }
func nya() -> String
mutating func sleep()
func clone() -> Self
func cast<T>(to: T.Type) -> T?
}
class Cat : CatProtocol {
required init() {}
let array = [2, 3, 3, 4, 7, 2, 1, 4, 0, 9, 1, 2]
// array の要素の値ごとに集計
// 2 が 3 個、 3 が 2 個 などを知りたい
let nToCount: [Int: Int] = array.reduce(into: [:]) { nToCount, n in
nToCount[n, default: 0] += 1
}
// 結果を表示
for (n, count) in (nToCount.sorted { $0.key < $1.key }) {
let array = [2, 3, 3, 4, 7, 2, 1, 4, 0, 9, 1, 2]
// array の要素の値ごとに集計
// 2 が 3 個、 3 が 2 個 などを知りたい
var nToCount = [Int: Int]()
for n in array {
nToCount[n, default: 0] += 1
}
// 結果を表示
// destroyed by `-Ounchecked`
import Foundation
let a: Int
switch arc4random() % 3 {
case 0:
print("0")
a = 111
case 1: