【Swift】 文字コードの変換 を整理してみた

前にやってみた、これ。


2つの型(プロトコル)の間を相互に変換するだけでも、いろんな書き方があるのだな。

などと思いつつ気になってたのが文字コードの変換。

👉 文字コード - Wikipedia hatena-bookmark

今回、おおまかに整理しておきたい。

 

🧑🏻‍💻 String の内部エンコーディングは UTF-8

Swift 5 switches the preferred encoding of strings from UTF-16 to UTF-8 while preserving efficient Objective-C-interoperability.

👉 Swift.org - UTF-8 String hatena-bookmark

String 内部のエンコーディングは「UTF-8」になったらしいです。

 

🧑🏻‍💻 String、 Data とファイル間での相互変換

図で。大体こんな。

まずは、エンコーディングの引数名が、encoding:, using:, as: と多様なので初見、分かりづらかった。


「String から」または「Stringへ」変換する場合に

「相手」 (「変換先」または「変換元」) のエンコーディングを指定する。

String 自体は「UTF-8」として意識。

Data と ファイル間の変換にはエンコーディングの指定は不要。

Data はそれぞれに変換済みのバイトシーケンス。

 

🧑🏻‍💻 変換してみる

コードを書いて試してみます。

👉 【Swift】よく使いそうな String の format hatena-bookmark


"あいうえお"
  .data(using: .shiftJIS)!.map { String(format: "%02X", $0) }.joined()
// 10 bytes 82A082A282A482A682A8

からスタートして一通り。

以前書いた extension を使っています。

👉 【Swift】ファイルやディレクトリ操作するための extension をまずは作った hatena-bookmark

これで大体いけるはず。

注意としては、「変換できない文字もある」ということ。


o  Shift_JIS → UTF-8 
x  UTF-8     → Shift_JIS

対応する文字がない。

 

🧑🏻‍💻 参考

👉 String.Encoding | Apple Developer Documentation hatena-bookmark
👉 shiftJIS | Apple Developer Documentation hatena-bookmark
👉 init(data:encoding:) | Apple Developer Documentation hatena-bookmark
👉 init(contentsOf:encoding:) | Apple Developer Documentation hatena-bookmark
👉 data(using:allowLossyConversion:) | Apple Developer Documentation hatena-bookmark
👉 write(to:atomically:encoding:) | Apple Developer Documentation hatena-bookmark
👉 init(contentsOf:options:) | Apple Developer Documentation hatena-bookmark
👉 write(to:options:) | Apple Developer Documentation hatena-bookmark



【Swift】URL から パス と ファイル名 を区別する方法

ディレクトリを指すURL。


print(URL.documentsDirectory)

ファイルを指すURL。


print(URL.documentsDirectory.appending(component: "new.txt"))

ちょっと分かりづらいので置き換えて。

👉 【Swift】ファイルやディレクトリのパスが長すぎていやだ - URL.shortPath() hatena-bookmark


print(URL.documentsDirectory.shortPath())
// /HOME/Documents/

print(URL.documentsDirectory.appending(component: "new.txt").shortPath())
// /HOME/Documents/new.txt

そもそも、URL.path() は、

URLが


ディレクトリを指す場合は path() の末尾は「/ (スラッシュ)」

というきまりがありますね。

そこで、文字列の分割を2つの関数でやってみます。


let path = URL.documentsDirectory.shortPath()
print(path.split(separator: "/"))
print(path.components(separatedBy: "/"))

// ["HOME", "Documents"]
// ["", "HOME", "Documents", ""]

そんな違いがありますので components(separatedBy:) を使って、


let urlPath = URL.documentsDirectory.shortPath()
let components = urlPath.components(separatedBy: "/")
print("urlPath:", urlPath)
print("path:", components.dropLast().joined(separator: "/") + "/")
print("file:", components.last!)

// urlPath: /HOME/Documents/
// path: /HOME/Documents/
// file:


let urlPath = URL.documentsDirectory.appending(component: "new.txt").shortPath()
let components = urlPath.components(separatedBy: "/")
print("urlPath:", urlPath)
print("path:", components.dropLast().joined(separator: "/") + "/")
print("file:", components.last!)

// urlPath: /HOME/Documents/new.txt
// path: /HOME/Documents/
// file: new.txt

よって、components(separatedBy:) を使った場合、

最終の文字列は、


URLがディレクトリを指してる場合 → 空文字
URLがファイルを指してる場合    → ファイル名

ということになります、

という APIの仕様と既存関数の特性を使った文字列分割でした。

そもそもは、


URL.pathComponents


URL.lastPathComponent

では、ディレクトリかファイルかの区別がない。

ということからこんなことをやってしまいました。

 

🤔 参考


【Swift】ファイルやディレクトリ操作するための extension をまずは作った

ファイルの操作がなんか混乱してストレス。

直感的にまずは作っておく。


FileManager.default.showContents(.temporaryDirectory)

// /HOME/tmp/ 
// /HOME/tmp/.DS_Store [6 kB]
// /HOME/tmp/CFNetworkDownload_1Ji1Ym.tmp [1.8 MB]
// /HOME/tmp/CFNetworkDownload_3ravkG.tmp [1.8 MB]
// /HOME/tmp/CFNetworkDownload_ArezWZ.tmp [1.8 MB]
// /HOME/tmp/CFNetworkDownload_Q2vc3J.tmp [920 kB]
// /HOME/tmp/CFNetworkDownload_WnW3m7.tmp [1.8 MB]
// /HOME/tmp/CFNetworkDownload_s4wpzr.tmp [1.8 MB]

既存の URL、FileManager にぶつからないように作りたい。

あくまで、補助、簡素化。

使い勝手で Gist 更新していきたいです。

いまどきの スマホOS は必要以上の高機能で、

開発者向け SDK や public API までも初心者泣かせの仕様です。


 

🤔 参考

👉 【Swift】FileManager を使いたい hatena-bookmark
👉 【Swift】そのディレクトリ内を再帰的に確認する hatena-bookmark
👉 【Swift】ファイルやディレクトリのパスが長すぎていやだ - URL.shortPath() hatena-bookmark
👉 【Swift】URL で特定のディレクトリやファイルを指す hatena-bookmark
👉 【Swift】その URL が ファイル なのか ディレクトリ なのか 存在しないのか hatena-bookmark


【Apple WWDC24】Swift ネタをサンプルコードとともに眺めていくページ

いよいよです。



👉 WWDC24 - Apple Developer hatena-bookmark

Apple 公式の GitHub では、

「sample」

の prefix をつけてリポジトリを公開していますよね。

洗練されていて、Swift の方向性も示されてるようで。

👉 Repository search results hatena-bookmark

いや、もしかしたら、GitHub 公開は遅れるかもしれん。

(更新中 ...)



【macOS】Find and remove all .DS_Store files

🧑🏻‍💻 Terminal から .DS_Store を消す方法

MacのFinderは、各フォルダのメタデータを保存するために .DS_Store ファイルを生成します。しかし、これらのファイルが不要な場合や煩わしい場合もあります。カレントディレクトリ配下のすべての .DS_Store ファイルを確認するには、以下のコマンドを使用します。


find . -type f -name ".DS_Store"

このコマンドは、現在のディレクトリとそのサブディレクトリ内のすべての .DS_Store ファイルをリストアップします。次に、これらのファイルを一括で削除するには、以下のコマンドを実行します。


find . -type f -name ".DS_Store" -delete

これにより、指定されたディレクトリ以下のすべての .DS_Store ファイルが削除され、ディレクトリがクリーンになります。

 

🧑🏻‍💻 .DS_Store ファイルの自動作成を制御する方法

ネットワークドライブや外部ドライブにアクセスする際に .DS_Store ファイルが生成されるのを防ぎたい場合、以下のコマンドを使って自動生成を停止できます。


defaults write com.apple.desktopservices DSDontWriteNetworkStores True
killall Finder

この設定により、これらのドライブに対して .DS_Store ファイルが作成されなくなります。必要に応じて、再度作成を許可する場合は、以下のコマンドを実行します。


defaults write com.apple.desktopservices DSDontWriteNetworkStores False
killall Finder

これにより、元の設定に戻すことができます。

 

🧑🏻‍💻 まとめ

.DS_Store ファイルはFinderのメタデータを保存するために重要な役割を果たしますが、時には不要で煩わしいこともあります。Terminalを使用してこれらのファイルを削除したり、自動生成を制御する方法を知っておくと、作業環境を整えるのに役立ちます。また、macOSのバージョンによっては .DS_Store ファイルの仕様が変わることがあるため、新しいバージョンにアップデートした際には設定を再確認することが重要です。これにより、効率的でスムーズな作業環境を維持できます。

 

🧑🏻‍💻 まとめ

結局、消さないほうがいい。

制御するなら以下のどれかで。


// newtork drive
defaults write com.apple.desktopservices DSDontWriteNetworkStores true
defaults write com.apple.desktopservices DSDontWriteNetworkStores false

// removable drive
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool true
defaults write com.apple.desktopservices DSDontWriteUSBStores -bool false

// finder
defaults write com.apple.finder AppleShowAllFiles -boolean false;killall Finder
defaults write com.apple.finder AppleShowAllFiles FALSE;killall Finder
defaults write com.apple.Finder AppleShowAllFiles TRUE;killall Finder
defaults write com.apple.finder AppleShowAllFiles -boolean true;killall Finder

.gitignore とかリモートクライアントの設定で操作するべし。

Apple の意図は汲んだほうがいいと思える。