【问题标题】:What is happening during the String.initString.init 期间发生了什么
【发布时间】:2021-05-22 13:17:29
【问题描述】:

我发现这个示例函数接受一个整数,然后将数字从大到小排序。示例输入:12345 输出:54321。该解决方案有效,但我试图理解 String.init 部分。谁能解释一下是怎么回事?

func descendingOrder(of number: Int) -> Int {
    let s =  String(number).sorted().reversed()
    return Int(s.compactMap(String.init).joined())!
}

【问题讨论】:

    标签: swift string initialization


    【解决方案1】:

    sReversedCollection<[String.Element]> 类型,所以它使String.Element 转换为String 这就是String.initcompactMap 循环内的含义

    当您看到 DataType.init 时,您需要知道被循环的项目是该类型的 init 的参数,因此在 String 的字符上发生循环以生成新的 [String] 作为结果

    开发者把这条线复杂化了,可以简化成这样,方便网友理解

    func descendingOrder(of number: Int) -> Int {
        let s =  String(number).sorted().reversed() // sort and reverse the string descendinng 
        let arr = s.compactMap(String.init) // convert characters to array of strings
        let joined = arr.joined() // join them in 1 string
        let res = Int(joined)! // convert string to int
        return res
    }
    

    或在 cmets 中

    func descendingOrder(of number: Int) -> Int {
        let s =  String(number).sorted().reversed() // sort and reverse the string descendinng
        let arr = s.map{ String($0) } // convert characters to array of strings
        let joined = arr.joined() // join them in 1 string
        let res = Int(joined)! // convert string to int
        return res
    }
    

    【讨论】:

    • 添加此示例以获得更好的解释:Int(s.compactMap({String($0)}).joined())!
    • 我认为compactMap 中的元素是Character 所以String.init 自动调用String.init(_ c: Character)
    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    相关资源
    最近更新 更多