ざっくりん雑記

プログラミングで忘れそうなことをひたすらメモる

Swift - 複数の条件式を書く

複数の条件式を書く時

Swiftのif文においては複数の条件式をカンマ区切り書くことができて、良い。

func judgmentPassOrFailTest(math:UInt, english:UInt) {
    if math >= 60, english >= 60, math+english >= 120 {
        print("あなたは合格です!", terminator: "/")
    } else {
        print("あなたは残念ですが, 不合格です", terminator: "/")
    }
    print("数学:\(math), 英語:\(english), 合計:\(math+english)")
}

judgmentPassOrFailTest(math: 56, english: 90)
judgmentPassOrFailTest(math: 63, english: 10)
judgmentPassOrFailTest(math: 62, english: 61)
あなたは残念ですが, 不合格です/数学:56, 英語:90, 合計:146
あなたは残念ですが, 不合格です/数学:63, 英語:10, 合計:73
あなたは合格です!/数学:62, 英語:61, 合計:123

参考

Swift - レンジ演算子

レンジ演算子

レンジ演算子は、数値の範囲を指定できる演算子で、for文などで使います。

書式
開始値..<終了値
開始値…終了値

数値が範囲内にあるかどうかを調べるとき

おもしろい範囲の調べ方ができる…(じぶんにとって見たことがない記法だった)

let range = 1...5
print(range.contains(1))
print(range.contains(3))
print(range.contains(5))
print(range.contains(100))
true
true
true
false

for inでレンジ演算子を使う

for-in文における使い方は以下のようなかたち。

for i in (1..<5) {
    print("\(i) 回目")
}

for i in (1...5) {
    print("\(i) 回目")
}
1 回目
2 回目
3 回目
4 回目
--
1 回目
2 回目
3 回目
4 回目
5 回目

参考

Swift - タプル

タプル

タプルは、複数の値を1個の値として扱えることが可能となる。1個の変数に複数の値を代入したり、関数で複数の値を返すこともできる。

宣言と代入

書式
(値1, 値2, ...)

たとえば、以下のような使い方ができる。

let book = ("Let's Swift!", 1200)
var sushikun:(String, Int, String) = ("おいしい", 200, "マグロ")

print(book)
print(sushikun)
("Let\'s Swift!", 1200)
("おいしい", 200, "マグロ")

ちなみに、型を指定していない場合は最初に代入した値をもとに型推論がされるため注意が必要。

let book = ("Let's Swift!", 1200)

book = ("Let's Android", "book")
error: cannot assign value of type 'String' to type 'Int'
book = ("Let's Android", "book")

値を取り出す

タプルに代入された値を取り出す際は、以下のように受け取る。

var book = ("Let's Swift!", 1200)
var (bookName, bookPrice) = book
print(bookName, bookPrice, separator: "/")
Let's Swift!/1200

以上のように、タプルに代入された値の数と受け取りたい数が一致していれば良いが、本の名前だけを取得したい、という場合には_というワイルドカードを使用すれば必要な値のみ受け取ることが可能になる。

var book = ("Let's Swift!", 1200)
var (bookName, _) = book
print(bookName)
Let's Swift!

タプルの値にインデックス番号でアクセス

先程の値を取り出す方法だと、たくさんの値が含まれたタプルの最後の値を取り出したい時に煩雑なコードになってしまう。

タプルはインデックス番号でアクセスすることも可能であるので、上記のような場合はこちらを利用したほうが見通しがよくなる。

var book = ("Let's Swift!", "Let's Xcode", "Let's Macbook", "Let's note")
print(book.3)
Let's note

タプルの値にラベルを付ける

それぞれの値がどういうものなのか、ラベルを付けることで区別することができる。

var book = (name: "Let's Swift!", price: 1500, isbn: "134321234532")
print(book.name)
Let's Swift!

参考

Swift - キャストする

Swiftでのキャスト

Swiftは定数や変数の型を厳密にチェックする性質を持っている。したがって、Double型にInt型の変数の値を代入しようとしたり、引数の型がInt型と定義しているところにDouble型が渡されるとエラーとなる。

そういった場合にキャストを使い、どちらか一方の型を合わせてあげる必要がある。

IntとDoubleの場合

let count = 1
let price = 100
let tax = 1.08

let sum = price * count * tax

この場合の結果は以下のとおり。

error: binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
let sum = price * count * tax
          ~~~~~~~~~~~~~ ^ ~~~

Int型とDouble型は掛け算できない、とエラーが出る。

そのため、price * countをDouble型にキャストしてあげる必要がある。

let count = 1
let price = 100
let tax = 1.08

let sum = Double(price * count) * tax
108

計算が正常に行われたことがわかる。

Stringと数値を連結させるときのキャスト

文字列と文字列においては+演算子で連結させることができる。しかし、文字列と数値型を+演算子で連結させようとするとエラーとなる。

こちらも、数値型をString型にキャストしてあげる必要がある。

let weather = "雪"
let temp = 0

print("きょうのてんきは" + weather + "、気温は" + String(temp) + "度となっています。")
きょうのてんきは雪、気温は0度となっています。

参考

Swift - デバッグ用関数

デバッグするときに便利な関数

出力変数 print()

デバッグの出力表示時に区切り文字を明示的に指定できたり、終端文字を指定できたりします。

書式

print(値1, 値2, ...separator: 区切り文字, terminator: 終端文字)

コード

let debugTest = "debug test"
let debugTest2 = "DEBUG TEST"

print(debugTest)
print(debugTest2)

出力

debug test and DEBUG TEST.

terminatorはこんな感じで使える。

コード

let mobileA = "Android"
let mobileB = "iOS"
let mobileC = "WindowsPhone"

print(mobileA, mobileB, separator: ",", terminator: "の2強状態の日本.")
print(mobileC, terminator: "はどこへ行ったのか.")

出力

Android,iOSの2強状態の日本.WindowsPhoneはどこへ行ったのか.

参考

sudo: no tty present and no askpass program specified setup の対処方法

動作環境

ホスト

  • OS X El Capitan 10.11.6

ゲスト(Vagrant

エラー内容と対処

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Fixed port collision for 22 => 2222. Now on port 2200.
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 3000 => 3000 (adapter 1)
    default: 22 => 2200 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2200
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
[default] GuestAdditions seems to be installed (5.0.26) correctly, but not running.
sudo: no tty present and no askpass program specified
sudo: no tty present and no askpass program specified
==> default: Checking for guest additions in VM...
The following SSH command responded with a non-zero exit status.
Vagrant assumes that this means the command failed!

sudo: no tty present and no askpass program specified setup

Stdout from the command:



Stderr from the command:

sudo: no tty present and no askpass program specified

なんかsudoが〜と言っているので、その設定を見直す。

[vagrant@localhost ~]$ sudo visudo

Defaults !visiblepwコメントアウトして、Defaults visiblepwを追記。 一応 vagrantユーザにroot権限が与えられているかも確認する。

# Defaults !visiblepw
Defaults visiblepw

root    ALL=(ALL:ALL) ALL
vagrant ALL=(ALL) NOPASSWD:ALL

保存して、一度vagrantから抜ける。

$ vagrant reload
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Fixed port collision for 22 => 2222. Now on port 2200.
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 3000 => 3000 (adapter 1)
    default: 22 => 2200 (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2200
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Connection timeout. Retrying...
    default: Warning: Connection timeout. Retrying...
==> default: Machine booted and ready!
[default] GuestAdditions 5.0.26 running --- OK.
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /Users/hoge/
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.

いけた!

参考

Jenkinsでsudo実行時のエラー - Qiita

Mac - ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

動作環境

突然MySQLが起動しなくなった

# mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

解決方法

/tmp/mysql.sockがないことが原因なので作る

$ sudo touch mysql.sock
$ sudo mysql.server start
Starting MySQL
. ERROR! The server quit without updating PID file (/usr/local/var/mysql/xxxxx.local.pid).

今度は権限が適切に与えられていないため、権限を付与する

$ sudo chown -R _mysql:_mysql /usr/local/var/mysql
$ sudo mysql.server restart
 ERROR! MySQL server PID file could not be found!
Starting MySQL
. SUCCESS!

MySQLサーバーが無事立ち上がったのでログインしてみる

# mysql -u root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.13 Homebrew

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

動いた!

参考