Does Swift init(count:, repeatedValue:) work?

前端 未结 6 2364
暗喜
暗喜 2021-02-18 15:04

Tested this from the reference: https://developer.apple.com/documentation/swift

var string = String(count: 5, repeatedValue: \"a\")
// string is \"aaaaa\"
         


        
6条回答
  •  离开以前
    2021-02-18 15:37

    I know this is an old question and already has an answer. However I think I know why String(count: 5, repeatedValue: "a") does not work.

    The thing is String has two similar looking initialisers:

    init(count: Int, repeatedValue: Character)
    init(count: Int, repeatedValue: UnicodeScalar)
    

    So in this case compiler can't tell whether a literal is a Character or UnicodeScalar, hence compile time error if you don't pass explicit Character. To confirm that "a" can be interpreted as UnicodeScalar you can check that this line compiles:

    let a: UnicodeScalar = "a"
    

提交回复
热议问题