LoginSignup
1
1

More than 5 years have passed since last update.

Swiftで同じ値を繰り返す文字列、配列

Last updated at Posted at 2018-05-27

Swift3で同じ値を繰り返す文字列、配列のコンストラクタの記法が変わっていたため、個人的にメモしました。

// Swift 2.3
let str = String(count: 10, repeatedValue: Character("s")) // "ssssssssss"
let arr = Array(count: 10, repeatedValue: "s") // ["s", "s", "s", "s", "s", "s", "s", "s", "s", "s"]

// Swift 3.0
let str = String(repeating: "s", count: 10) // "ssssssssss"
let arr = Array(repeating: "s", count: 10) // ["s", "s", "s", "s", "s", "s", "s", "s", "s", "s"]

Swift3からStringとArrayのコンストラクタのpublic init(count: Int, repeatedValue: Element)public init(repeating repeatedValue: Element, count: Int)に変更されました。どちらもtupleをコンストラクタに渡して生成する方法なのですが、個人的にはイマイチSwift3の変更点と噛み合ってない気がします。

// Swift 2.3
func hoge(param1: Int, param2: Int) {
    ...
}

func fuga(param0 param1: Int, param2: Int) {
    ...
}

hoge(0, param2: 1)
fuga(param0: 0, param2: 1)

// Swift 3.0
func hoge(param1: Int, param2: Int) {
    ...
}

func fuga(param0 param1: Int, param2: Int) {
    ...
}

hoge(param1: 0, param2: 1)
fuga(param0: 0, param2: 1)

Swift3からfunction callの第1引数のラベル名の省略がされなくされました。ですので、上で紹介したコンストラクタもrepeatingというラベル名をわざわざ設定しなくてもrepeatedValueというラベル名が必須なるので必要ないのかなと感じました。

ちなみに型を調べるのに使うdynamicTypetype(of: Element)に変更されていました。

// Swift 2.3
let tpl1 = (count: 10, repeatedValue: "s")
let tpl2 = (10, "ssssssssss")

print(tpl1.dynamicType) // (Int, String)
print(tpl2.dynamicType) // (Int, String)

print(tpl1.count) // 10
print(tpl2.0) // 10

// Swift 3.0
let tpl1 = (count: 10, repeatedValue: "s")
let tpl2 = (10, "ssssssssss")

print(type(of: tpl1)) // (Int, String)
print(type(of: tpl2)) // (Int, String)

print(tpl1.count) // 10
print(tpl2.0) // 10

同じ値を繰り返す文字列、配列などはプロダクションコードではあまり使う機会がないかもしれないのですが、デバッグなどのちょっとした処理を書くときに結構使うことがあります。こういう点も意外と変更されているので注意が必要ですね。ただ、今回の変更に関してはイマイチ納得感はなかったです。何かこの変更の理由をご存じの方がいらっしゃいましたら、教えていただけると助かります。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1