LoginSignup
3
2

More than 5 years have passed since last update.

Swiftで文字列を繰り返す

Posted at

RubyやPythonでできる文字列を指定した回数だけ繰り返して文字列を作るやつ

文字列 * 回数

をSwiftでもやりたくなった。

func * (lhs: String, rhs: Int) -> String {
    var newStr = ""
    for _ in 1...rhs {
        newStr += lhs
    }
    return newStr
}

"無駄!" * 10

無駄にワンライナー

func * (lhs: String, rhs: Int) -> String {

    return (1...rhs).reduce(""){ $0.0 + lhs }

}

"無駄!" * 10

演算子オーバーロードとか普段使わないのでなんか満足!

3
2
4

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
3
2