dev._.note

[Swift] init(repeating:count:) 본문

Dev/SWIFT

[Swift] init(repeating:count:)

Laena 2023. 10. 27. 15:24

👏 init(repeating:count:) 

Creates a new string representing the given string repeated the specified number of times.

지정된 횟수만큼 반복된 주어진 문자열을 나타내는 새 문자열을 만듭니다.

 

String과 Array에서 사용할 수 있다. 배열크기와 초기값을 넣어줄 수 있으며, 특정 값을 반복하여 값을 만들 수 있다.
repeating에 반복할 문자, 문자열, 숫자, 부울 등을 넣어주면 되고, count에는 반복 횟수를 넣어주면 된다.


📌 공식문서에서의 사용법

init(
    repeating repeatedValue: String,
    count: Int
)

 

Arry 예시

// [Int](repeating: 0, count: 5)와 같음
let input = Array(repeating: 0, count: 5)
print(input) // [0, 0, 0, 0, 0]

let input = [String](repeating: "c", count: 5)
print(input) // ["c", "c", "c", "c", "c"]

 

String 예시

let co4 = String(repeating: "co", count: 4)
print(co4) // cocococo

let ch = Character(readLine()!) // G
print(String(repeating: ch, count: 4)) // GGGG

 

Apple 공식문서

https://developer.apple.com/documentation/swift/string/init(repeating:count:)-23xjt

 

init(repeating:count:) | Apple Developer Documentation

Creates a new string representing the given string repeated the specified number of times.

developer.apple.com

 

'Dev > SWIFT' 카테고리의 다른 글

[Swift] Swift 란?  (1) 2023.10.28
[Swift] prefix 와 suffix  (0) 2023.10.27
[Swift] enumerated() 배열의 인덱스 가져오기  (0) 2023.10.26
[Swift] zip 함수  (0) 2023.10.26
[Swift] reverse() 와 reversed()의 차이점  (1) 2023.10.25