swift错误的String init(格式...方法?

dop*_*pcn 5 string swift

let elem1 = "1"
let elem2 = "2"
let array = [elem1, elem2]
let format = "%@ != %@"

//compiler error
//can't find an initializer for type...
let str = String(format: format, arguments: elem1, elem2)

//no errors but wrong output
//("%@ != %@", "1", "2")
let str = String(format: format, _arguments: elem1, elem2)

//runtime error
//fatal error: can't unsafeBitCast between types of different sizes
//this is what I need
let str = String(format: format, arguments: array)

//only this works with the right output
//1 != 2
let str = String(format: format, arguments: [elem1, elem2])

print(str)
Run Code Online (Sandbox Code Playgroud)

在xcode7 beta和xcode6.3中测试过,我现在找不到解决方法

Lau*_*ent 5

使用此语法(XCode 7):

import Foundation

let elem1 = "1"
let elem2 = "2"
let format = "%@ != %@"
let str = String(format: format, elem1, elem2) // "1 !=2"
print(str) // "1 != 2\n"
Run Code Online (Sandbox Code Playgroud)

诀窍是用 format: 指定重载的构造函数:并跳过参数:一起。


归档时间:

查看次数:

3197 次

最近记录:

9 年,8 月 前