Created
September 5, 2017 02:35
-
-
Save mitsuse/fe8e31f9fe13ece8db06ad8c5e0a4e3f to your computer and use it in GitHub Desktop.
Swift の string interpolation (文字列補間) は型の変更を検出できないので事故しやすい話.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
オブジェクトを文字列へ変換する際に, string interpolation を直接使っていると, 変換前の値の型に何らかの変更 (例では
cat1
がcat2
に置き換わったケース, やや極端な例なので名前の問題にも見える) が入った場合, 事故しやすい. ありがちなのが model の状態を view の表現に変換する場合. 変換前の型の記述と変換処理の記述がレイヤー的にも離れているので, どちらも合わせて変更しなければならないことを見落としがち. 変換処理付近に静的に型チェックをするコード (例では function で string interpolation しているコードを包んでいる) を入れておくのがいいのではなかろうか.