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

回眸只為那壹抹淺笑 提交于 2019-12-05 09:54:02

问题


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

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

I got this error:

Playground execution failed: error: :5:14: error: could not find an overload for 'init' that accepts the supplied arguments var string = String(count: 5, repeatedValue: "a")

Does this actually work?


回答1:


It seems that you have to explicitly pass in a Character type to it to function. This works for me.

let char = Character("a")
let string = String(count: 5, repeatedValue: char)

Although, there may be bug mixed in with all this as well. I believe the way you were doing this should have worked on its own. And I can't seem to get code completion on this initializer at all.

Edit: I'm going with bug. The following compiles just fine.

let array = Array(count: 5, repeatedValue: "a")



回答2:


For the benefit of future searchers: as of Swift 3, use init(repeating:count:).




回答3:


This works just fine :

var str9 = String(count: 5,repeatedValue: Character("c"))



回答4:


For anyone in swift 3.x its now something like this this will work like a charm.

var string = String(repeating: "a", count: 5)



回答5:


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"



回答6:


Swift 3:

var array = Array(repeating: 0, count: 5)

Output: [0, 0, 0, 0, 0]



来源:https://stackoverflow.com/questions/24463155/does-swift-initcount-repeatedvalue-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!