Can You Use String/Character Literals Within Swift String Interpolation

Can you use string/character literals within Swift string interpolation?

It can be done starting in Swift 2.1:
http://www.russbishop.net/swift-2-1

Prior to that, it wasn't possible.

Literals in string interpolation expression

The documentation seems to suggest that escaping literals in interpolated strings is somehow possible

The expressions you write inside parentheses within an interpolated string cannot contain an unescaped double quote (") or backslash (), and cannot contain a carriage return or line feed.

However, to the best of my knowledge, there's currently no way.

Possible workarounds are string concatenation:

"Number of items: " + (items > 0 ? "\(items)" : "zero")

or simply using a variable

let nOfItems = items > 0 ? "\(items)" : "zero"
"Number of items: \(nOfItems)"

Swift: Provide default value inside string literal

Just wrap it in parentheses:

print("Error \((response.result.error ?? "default value"))")

The cleaner way is to use @Alladinian answer and put the string in a variable before printing it

Difference between String interpolation and String initializer in Swift

String interpolation "\(item)" gives you the result of calling description on the item. String(item) calls a String initializer and returns a String value, which frequently is the same as the String you would get from string interpolation, but it is not guaranteed.

Consider the following contrived example:

class MyClass: CustomStringConvertible {
var str: String

var description: String { return "MyClass - \(str)" }

init(str: String) {
self.str = str
}
}

extension String {
init(_ myclass: MyClass) {
self = myclass.str
}
}

let mc = MyClass(str: "Hello")
String(mc) // "Hello"
"\(mc)" // "MyClass - Hello"

Swift: string with placeholder for variables to be passed in during 'print()'

Normally in Swift you can just use String Interpolation \(). This is just like Python's f-strings.

let color = "purple"
let size = "large"
print("My car is the \(color) one over there.") /// My car is the purple one over there.
print("My car is the \(size) one over there.") /// My car is the large one over there.

That should be fine for most cases. But if you want an explicit placeholder, check out init(format:_:).

let color = "purple"
let size = "large"
let description = "My car is the %@ one over there."
print(String(format: description, color)) /// My car is the purple one over there.
print(String(format: description, size)) /// My car is the large one over there.

Use %@ for String values like color. Here's the full list of placeholders, in case you want format an Int or something else.



Edit: Based off OP's code snippets

Your first code snippet compiles fine for me. However, %@ only supports String and other objects that bridge to obj-c — Bools like hilarious don't work. You need to convert it to a String first.

let hilarious = false
let joke_evaluation = "Isn't that joke so funny?! %@"
print(String(format: joke_evaluation, arguments: [String(hilarious)])) /// Need to convert `hilarious` to a String first

Result:

Isn't that joke so funny?! false

Your second code snippet has a couple problems. I think you might be confusing Apple structs like String with custom, made-by-you structs like CarStuff. But anyway, if you want to make your own struct CarStuff (again, why?), here's how:

  • carStuff is a struct, so it should be capitalized to CarStuff (just good conventions).
  • The purpose of an initializer is to initialize all of the struct's properties.
  • structs get initializers for free, so you don't need to define one. But if you want to make your own, you need to make sure that all the properties are initialized once init() is called. See the docs for more information.
  • Your initializer, init(format: String, arguments: [CVarArg]), doesn't have a body. This is a syntax error - you need the curly braces {}.
  • Also, why is your initializer defined as init(format: String, arguments: [CVarArg])? The properties of CarStuff are color, size, and description. What does format and arguments have to do with those? Remember: The purpose of an initializer is to initialize all of the struct's properties.
init(format: String, arguments: [CVarArg]) {
/**
initialize the struct's properties here.
but, you already provided default values to the properties...
... for example, `let color = "red"`
so you don't even need your custom init — Swift does it automatically for you.
And besides, what is `format` and `arguments` for?
Just remove this `init` entirely.
*/
}

Anyway, all of that was just some extra info, not really related to your original question. The real problem is that there are 2 very similar String initializers:

  • init(format:arguments:)
  • init(format:_:)

The first one requires you to pass in an Array. The second one takes in a variadic number of parameters, so you can just directly pass in your variable to be substituted.

struct CarStuff {
let color = "red"
let size = "large"
let description = "The %@ car."
}
let carStuff = CarStuff() /// initialize a `CarStuff` (using Swift's auto-generated initializer)
print(String(format: carStuff.description, arguments: [carStuff.color])) // init(format:arguments:) requires an array
print(String(format: carStuff.description, carStuff.color)) // init(format:_:) lets you omit `arguments` and directly pass in your arguments

Result:

The red car.

The red car.

How can i split character with string which has multiple characters

Other than split, there is also a method called components(separatedBy:) that accepts a StringProtocol as the parameter:

"111---222-333".components(separatedBy: "---")

(Escaped) double quotes in string interpolations (in Swift)

@Daniel answer is good, but in your case you could use the builtin capitalizedString method.

let s =  "hours".capitalizedString

or

let s =  "\n hours".capitalizedString

This method capitalize the first letter of each word.
Edit:

let s =  (capitalized ? "hours".capitalizedString : "hours")

Double quotes(escape character) inside String(format: ) in swift

Just do:

let timeString = String(format: "https://stackoverflow.com/character=\"inside\"").replacingOccurrences(of: "\"", with: "")

This will output as:

https://stackoverflow.com/character=inside

Replace the occurrences of " with nothing.

Happy coding!



Related Topics



Leave a reply



Submit