0

It's a leetcode problem: 168. Excel Sheet Column Title @ https://leetcode.com/problems/excel-sheet-column-title/


The code works fine at my mac, but got compile error at leetcode:
Line 5: ambiguous use of 'init'
So, please tell me which String.init method does this code call?

String(UnicodeScalar(val))
And how I can solve this issue?


class Solution {
    func convertToTitle(n: Int) -> String {
        var alphabet = [String]()
        var result = ""
        alphabet = (UnicodeScalar("A").value...UnicodeScalar("Z").value).map({(val: UInt32) -> String in return String(UnicodeScalar(val)); })
        var num = n
        while num != 0 {
            num -= 1
            result = alphabet[num % 26] + result
            num /= 26
        }
        return result
    }}

2 Answers2

0

This compiles in the latest Xcode, so I assume it's an issue with leetcode's compiler.

I believe the initializer that's supposed to get called here is init<T>(_: T). I don't know what other initializer their compiler is finding.

As for how to fix it, you could try something like String(UnicodeScalar(val) as CustomStringConvertible).

phu
  • 1,199
  • 2
  • 10
  • 20
  • sorry,still got the same compile error,I wrote a letter to leetcode, they said they uses the latest swift compiler from github.So best practice still not found. – user2710368 Mar 10 '16 at 09:00
0

This compiles for me under linux on 2.2.1 and 3.0 Preview 1, but I ran across a similar problem in calling the UnicodeScalar constructor with single-character strings (UnicodeScalar("A")). Instead, try assigning the string values directly to UnicodeScalar-typed variables:

let a : UnicodeScalar = "A"
let z : UnicodeScalar = "Z"
let alphabet = (UnicodeScalar("A").value...UnicodeScalar("Z").value).map({(val: UInt32) -> String in return String(UnicodeScalar(val)); })