5
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)

tested in xcode7 beta and xcode6.3, I couldn't find a workaround right now

2
  • Have you tried using NSString instead of String? Commented Jun 18, 2015 at 2:31
  • 1
    @LeoDabus is right and the reason why String(format: format, arguments: array) doesn't work is here stackoverflow.com/questions/24024376/… Commented Jun 18, 2015 at 2:42

1 Answer 1

5

Use this syntax (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"

The trick is to specify the overloaded ctor with format: and skip arguments: all together.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.