SwiftはPythonに似ている
2022-12-17
西本 卓也 @nishimotz / @24motz
Shuaruta Inc.
1
2
6/25 オープンセミナー2022@広島
• Re: エンジニアのための統計・データ分析入門
3
Swift Charts: Raise the bar
• アクセシブルなデータ可視化
4
SwiftUI のために Swift を学ぶ
5
Python の教材を Swift に移植できるか
6
swift repl
7
swift package init
% mkdir hello
% cd hello
% swift package init --name hello --type executable
Creating library package: hello
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/hello/hello.swift
Creating Tests/
Creating Tests/helloTests/
Creating Tests/helloTests/helloTests.swift
8
Sources/hello/hello.swift
@main
public struct hello {
public private(set) var text = "Hello, World!"
public static func main() {
print(hello().text)
}
}
9
swift run
% swift run
Building for debugging...
[3/3] Linking hello
Build complete! (0.96s)
Hello, World!
% file ./.build/x86_64-apple-macosx/debug/hello
./.build/x86_64-apple-macosx/debug/hello: Mach-O 64-bit executable x86_64
10
Swift は Python に似ている(こともある!)
# Python
for animal in ["cat", "dog", "snake"]:
print(animal)
// Swift
for animal in ["cat", "dog", "snake"] {
print(animal)
}
Pythonに似ている例を探そう
11
12
タプルの代入
# Python
dog, cat = ("dog", "cat")
print(dog, cat)
// Swift
var (dog, cat) = ("dog", "cat")
print(dog, cat)
13
let と var
// JavaScript の分割代入
let [dog, cat] = [“dog”, “cat”] // 変数(ブロックスコープ)
var [dog, cat] = [“dog”, “cat”] // 変数(グローバル)
// 定数は const
// Swift
let は定数
var は変数
14
Swiftのタプルはシーケンスではない
var animals = ("dog", "cat")
print(animals)
print(animals.0)
print(animals.1)
// for animal in animals {
// print(animal)
// }
// エラーになる
15
Pythonの正規表現
import re
s = "My name is Taylor and I'm 26 years old."
m = re.search("My name is (.+?) and I'm (d+) years old.", s)
if m:
print(f"Name:{m.group(1)}")
print(f"Age:{m.group(2)}")
16
Swiftの正規表現
let s = "My name is Taylor and I'm 26 years old."
let m = /My name is (.+?) and I'm (d+) years old./
if let g = try? m.wholeMatch(in: s) {
print("Name: (g.1)")
print("Age: (g.2)")
}
// since Swift 5.7
17
SwiftUI で押すとアラートが出る例
18
The craft of SwiftUI API design: Progressive disclosure
struct ContentView: View {
@State private var didSave = false
var body: some View {
Button(“Hello") {
didSave = true
}
.alert("Saved.", isPresented: $didSave) {
Button("OK") {
print("OK is pressed")
}
}
}
}
19
末尾クロージャー
// Swift
var names = ["cat", "snake”, "dog"]
names.sorted { $0.count < $1.count }
# Ruby
names = ["cat", "snake”, "dog"]
names.sort { _1.length <=> _2.length } # since Ruby 2.7
# => ["cat", "dog", "snake"]
SwiftはRubyに似ている
20
21
12/28 すごい広島 .rb with Python

221217 SwiftはPythonに似ている