Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Created September 5, 2017 02:35
Show Gist options
  • Save mitsuse/fe8e31f9fe13ece8db06ad8c5e0a4e3f to your computer and use it in GitHub Desktop.
Save mitsuse/fe8e31f9fe13ece8db06ad8c5e0a4e3f to your computer and use it in GitHub Desktop.
Swift の string interpolation (文字列補間) は型の変更を検出できないので事故しやすい話.
struct Cat {
let name: String
let age: Int
}
let cat1 = "jiji"
let cat2 = Cat(name: "jiji", age: 13)
print("name: \(cat1)") // name: jiji
print("name: \(cat2)") // name: Cat(name: "jiji", age: 13)
struct Cat {
let name: String
let age: Int
}
let cat1 = "jiji"
let cat2 = Cat(name: "jiji", age: 13)
func interpolated(_ name: String) -> String {
return "name: \(name)"
}
print(interpolated(cat1)) // name: jiji
// print(interpolated(cat2)) // error: cannot convert value of type 'Cat' to expected argument type 'String'
print(interpolated(cat2.name)) // name: jiji
@mitsuse
Copy link
Author

mitsuse commented Sep 5, 2017

オブジェクトを文字列へ変換する際に, string interpolation を直接使っていると, 変換前の値の型に何らかの変更 (例では cat1cat2 に置き換わったケース, やや極端な例なので名前の問題にも見える) が入った場合, 事故しやすい. ありがちなのが model の状態を view の表現に変換する場合. 変換前の型の記述と変換処理の記述がレイヤー的にも離れているので, どちらも合わせて変更しなければならないことを見落としがち. 変換処理付近に静的に型チェックをするコード (例では function で string interpolation しているコードを包んでいる) を入れておくのがいいのではなかろうか.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment