0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift チートシート

Posted at

環境

Raspberry Pi : 5

$ cat /etc/debian_version
12.5

Swift インストール

1. swift-arm を入手

$ curl -s https://packagecloud.io/install/repositories/swift-arm/release/script.deb.sh | sudo bash

2. install

$ sudo apt install swiftlang -y

なんか Runtime 出るけどまぁいいや

実行

test.swift
print("hello")

即時実行

$ swift test.swift
hello

コンパイル

$ swiftc test.swift
$ ./test
hello

-o file で命名出力できる

本文

箱(変数とか)

変数

型は大文字から始める
型は推論される

test.swift
var v1 = 42
var v2 :Int = 42
var v3 :Int
v3 = 42

print(v1, v2, v3)
$ swift test.swift
42 42 42

定数

test.swift
let v1 = 42
let v2 :Int = 42
let v3 :Int
v3 = 42

print(v1, v2, v3)

実行結果は一緒

配列

既知

test.swift
let arr = [0, 1, 42]

print(arr[0], arr[1], arr[2])
$ swift test.swift
0 1 42

未知

test.swift
var arr :[Int]
arr = Array(repeating: 0, count: 3)

print(arr.count)

配列の要素数は 配列名.count で取得できる

$ swift test.swift
3

enum

数値

test.swift
enum eNameNum :Int32 {
	case hoge
	case fuga
	case piyo
}

print(eNameNum.piyo)
print(eNameNum.piyo.rawValue)

指定した型を取得する場合は enume名.enum定数名.rawValue

$ swift test.swift
piyo
2

nil 許容と nil 切り落とし

test.swift
var hoge :Int? = 42
print(hoge!)

hoge = nil
print(hoge)

型名? で nil を扱える型になる
一方で 変数名! で nil が入っていない変数として扱える

$ swift test.swift
42
nil

関数とか

基本

test.swift
func add(va :Int, vb :Int) -> Int {
	print("a + b =", va + vb)
	return va + vb
}

func add(va :Int) -> Int {
	va + 1
}

var res = add (va :16, vb :26)
print(res)
res = add (va :16)
print(res)

オーバーロードは許される
例外的に1行の関数は return の省略が許されそう
関数のどの値に入れるか書かされるため筆記量は多い

$ swift test.swift
a + b = 42
42
17

複数戻り値

test.swift
func add(va :Int, vb :Int) -> (Int, String) {
	return (va + vb, "hello")
}

var res = add(va :16, vb :26)
print(res)
print(res.0)
print(res.1)
$ swift test.swift
(42, "hello")
42
hello

制御文

for in

test.swift
for i in 0 ..< 5 {
	print(i)
}
$ swift test.swift
0
1
2
3
4

if

test.swift
for i in 0 ..< 5 {
	if i % 2 == 0 {
		print(i, "eve")
	} else {
		print(i, "odd")
	}
}
$ swift test.swift
0 eve
1 odd
2 eve
3 odd
4 eve
0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?