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 3 iPhoneアプリ開発 入門ノート Swift3 + Xcode 8対応 (Oshige introduction note)
- 作者: 大重美幸
- 出版社/メーカー: ソーテック社
- 発売日: 2016/11/05
- メディア: 単行本
- この商品を含むブログを見る
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はどこへ行ったのか.
参考
詳細! Swift 3 iPhoneアプリ開発 入門ノート Swift3 + Xcode 8対応 (Oshige introduction note)
- 作者: 大重美幸
- 出版社/メーカー: ソーテック社
- 発売日: 2016/11/05
- メディア: 単行本
- この商品を含むブログを見る
sudo: no tty present and no askpass program specified setup の対処方法
動作環境
ホスト
- OS X El Capitan 10.11.6
ゲスト(Vagrant)
- vagrant 1.8.1
- Virtualbox 5.0.14
- CentOS 7.2
エラー内容と対処
$ 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.
いけた!
参考
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設定をぐぐってるような気がするので、記事としてまとめます。
環境について
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
にはその鍵の環境名などを入力すると複数環境がある場合だと区別しやすくなります。
Add SSH key
で登録します。
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.
お疲れ様でした!
参考
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
解決方法
$ brew install imagemagick
$ bundle install
Bundle complete!
参考
Rails - Viewでデバッグするならdebug
Viewをいじる時のデバッグ
Rails歴1ヶ月弱、きょうViewをいじっているときに便利だ!となって嬉しくなったメソッド、debug
を備忘録で残しておきます。
使い方はすごくかんたんで、インスタンス変数であれば
<%= debug @item %>
これだけで、変数値やパラメータ値が見やすく表示することができます。
また、開発中のみデバッグの値を表示したいといった場合は
<%= debug @item if Rails.env.development? %>
と 後置ifを使います。