ざっくりん雑記

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

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>

動いた!

参考

Unix上にいつものGit, GitHub環境をつくる

Vagrantなどで新しい仮想環境(Unix)を作るたびにGitの初期設定、GitHubとのSSH設定をぐぐってるような気がするので、記事としてまとめます。

環境について

  • OS X El Capitan ver.10.11.6
  • ターミナル(bash)

Gitをインストールする

$ sudo yum install git
...
インストール:
  git.x86_64 0:1.8.3.1-6.el7_2.1

依存性関連をインストールしました:
  libgnome-keyring.x86_64 0:3.8.0-3.el7             perl-Error.noarch 1:0.17020-2.el7
  perl-Git.noarch 0:1.8.3.1-6.el7_2.1               perl-TermReadKey.x86_64 0:2.30-20.el7
  rsync.x86_64 0:3.0.9-17.el7

完了しました!

git config 関連を設定する

これを設定しなくても致命的な問題はないですが、GitHub上でアカウントに紐付くEmailをローカルのGitに設定しておくことで、誰がコミットしたものなのかが判別できるようになります。(Git - アカウントの準備と設定

# 名前を設定する
$ git config --global user.name konnobu

# メールアドレスを設定する
$ git config --global user.email konnobu@email.com

# いい感じに出力をカラフルにする
$ git config --global color.ui true

GitHubと通信するためにSSH設定をする

鍵を作る

$ ssh-keygen -t rsa -C "your_mail_address@email.com"

Generating public/private rsa key pair.
Enter file in which to save the key (/home/vagrant/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/vagrant/.ssh/id_rsa.
Your public key has been saved in /home/vagrant/.ssh/id_rsa.pub.
The key fingerprint is:
a2:ee:0c:0c:f8:98:11:a1: your_mail_address@email.com
The key's randomart image is:
+--[ RSA 2048]----+
|.                |
|..               |
|.o..             |
|+.+dw            |
|.O..=...         |
|adsaw.. o        |
|   +. o .        |
+-----------------+

途中で、3回ほど任意のキーワードを入力する必要がありますが、基本的に何も入力せずにエンターのみで進んで大丈夫です。(ただ、パスフレーズを登録したほうがより安全とGitHubは言っています。)

鍵(公開鍵)を確認してコピーする

次に、鍵ができたので公開鍵を確認します。 場所は先程の鍵を作ったときにYour public key has been saved in /home/vagrant/.ssh/id_rsa.pub.というようになっているので、これをcatで出力します。

$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCrBHfcckGtnkj3N/8mzADcjMsPmh71BuUdwlokkvf7tzpn+R5jHzkKZnEcdbtrwYzrCxMOnrUXXM69gdxFBUCGl+zsDs0XEVMA3tRYEf3OISZAUw2UnVWlu7e8n28YqIZHuVAu5E/92l2zzpKDKuXNjY/dgcZ0jOzaKV2hQxYx84d7NgobQT1IsKyywaNlvdXkv09Y1zC8hF7f4br6iauXtFGC8RWlXcK26FsF6WqJDzX/4ucv6XrdpW2HcA/Nz/mr46/k4M/iA75L52w5JuFjftr81NoCbV2vzg8aDiYj26WInYxAyh4ZGKlEDVbHPhZ6Dq4/en7Wc7uio3NRf7yt "your_mail_address@email.com"

公開鍵の中身がバーっと表示されるので、これをまるっとコピーします。(ssh-rsa ... @email.com"の部分)

GitHub上に鍵を登録する

次に、GitHubにアクセスし、設定画面のSSH keysを表示します。

すると、以下のようなフォームがあるので、Keyには先ほどコピーした内容をペースト。Titleにはその鍵の環境名などを入力すると複数環境がある場合だと区別しやすくなります。

f:id:azuuun:20160730001654p:plain

Add SSH keyで登録します。

SSH接続ができるか確認する

以下を入力するとGitHubとのSSH通信を試行します。

$ ssh -T git@github.com

すると以下のように聞かれるので、yesでエンター。

The authenticity of host 'github.com (192.30.253.112)' can't be established.
RSA key fingerprint is 16:27:ac:a5:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes

Hi!と返ってきたら成功です。

Hi Konnobu! You've successfully authenticated, but GitHub does not provide shell access.

お疲れ様でした!

参考

GithubのSSH通信設定 - Qiita

Macでrmagickのbundle installに失敗したときの対処

エラー内容

Installing rmagick 2.15.4 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/azunobu/.rbenv/***/rmagick-2.15.4/ext/RMagick
/Users/azunobu/.rbenv/versions/2.3.0/bin/ruby -r ./siteconf20160704-56813-17nbb4t.rb extconf.rb
checking for clang... yes
checking for Magick-config... no
checking for pkg-config... yes
Package MagickCore was not found in the pkg-config search path.
Perhaps you should add the directory containing `MagickCore.pc'
to the PKG_CONFIG_PATH environment variable
No package 'MagickCore' found
checking for outdated ImageMagick version (<= 6.4.9)... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/azunobu/.rbenv/versions/2.3.0/bin/$(RUBY_BASE_NAME)

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/azunobu/.rbenv/***/rmagick-2.15.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/azunobu/.rbenv/***/gems/rmagick-2.15.4 for inspection.
Results logged to /Users/azunobu/.rbenv/***/rmagick-2.15.4/gem_make.out

解決方法

  1. $ brew install imagemagick
  2. $ bundle install
  3. Bundle complete!

参考

stackoverflow.com