include dictionary or array value in swift string with backslash notation
Single quotes are not allowed as string delimiters in Swift. Additionally the string interpolation does not allow ‘unescaped double quote (") or backslash (\)’, cf. The Swift Programming Language
If you have the key as a constant (or variable) it will work:
let key = "mine"
let str = "dictionary values are \(dict[key])"
As an aside Swift encourages immutability for safety, you should always use let
by default and only revert to var
if you really need to.
Swift : How to put string in \( )?
You can't put things with quotes in a \( )
, you'll need to assign it to a variable:
var dictionary = ["name": "henry", "age": "20"];
let name = dictionary["name"];
println("name = \(name)");
escape dictionary key double quotes when doing println dictionary item in Swift
Xcode 7.1+
Since Xcode 7.1 beta 2, we can now use quotations within string literals. From the release notes:
Expressions interpolated in strings may now contain string literals. For example, "My name is (attributes["name"]!)" is now a valid expression. (14050788)
Xcode <7.1
I don't think you can do it that way.
From the docs
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.
You'd have to use
let someVar = dict["key"]
println("Some words \(someVar)")
Swift string literal - remove escaping back slashes
You may be confusing how the IDE displays strings and the actual strings that would be printed. Setting breakpoints and looking at the debugger will show you C-escaped strings. If you print those values, the escaping will be gone. For example, if I create the literal string you're describing:
let string = #"[{"crawlLogic":{"startURL":"https://somesite.com/start","someParam":"\r\n\r\n/** Retrieves element's text either by class name""#
The debugger will print this value's debugDescription
which will include escaping (such as \"
and \\r
, note the double-backslash):
print(string.debugDescription)
"[{\"crawlLogic\":{\"startURL\":\"https://somesite.com/start\",\"someParam\":\"\\r\\n\\r\\n/** Retrieves element\'s text either by class name\""
But those extra escapes aren't actually in the string:
print(string)
[{"crawlLogic":{"startURL":"https://somesite.com/start","someParam":"\r\n\r\n/** Retrieves element's text either by class name"
If the debugDescription
has \r
rather than \\r
, then that's indicating you have a carriage return (UTF-8: 0x0d) in your string, not \r
(UTF-8: 0x5c 0x72). If you need to convert carriage return + newline into \r\n
, then you can do that with with replaceOccurrences(of:with:)
.
string.replaceOccurrences(of: "\r\n", with: #"\r\n"#)
This says to replace the string "carriage return, newline" with "backslash r backslash n."
(But I would first investigate why the string is in the wrong form to start with. I'm guessing you're constructing it with "\r\n"
at some point when you meant #"\r\n"#
or "\\r\\n"
. Or perhaps you're unescaping a string you were given when you shouldn't. Escaping and unescaping strings is very tricky. Try to build the string to hold the characters you want in the first place rather than trying to fix it later.)
If you continue to have trouble, I recommend converting your string into UTF-8 (Array(string.utf8)
) and looking at the actual bytes. This will remove all ambiguity about what is in the string.
How to print double quotes inside ?
With a backslash before the double quote you want to insert in the String:
let sentence = "They said \"It's okay\", didn't they?"
Now sentence
is:
They said "It's okay", didn't they?
It's called "escaping" a character: you're using its literal value, it will not be interpreted.
With Swift 4 you can alternatively choose to use the """
delimiter for literal text where there's no need to escape:
let sentence = """
They said "It's okay", didn't they?
Yes, "okay" is what they said.
"""
This gives:
They said "It's okay", didn't they?
Yes, "okay" is what they said.
With Swift 5 you can use enhanced delimiters:
String literals can now be expressed using enhanced delimiters. A string literal with one or more number signs (#) before the opening quote treats backslashes and double-quote characters as literal unless they’re followed by the same number of number signs. Use enhanced delimiters to avoid cluttering string literals that contain many double-quote or backslash characters with extra escapes.
Your string now can be represented as:
let sentence = #"They said "It's okay", didn't they?"#
And if you want add variable to your string you should also add #
after backslash:
let sentence = #"My "homepage" is \#(url)"#
Filtering dictionaries within array with JSON decoding based on latest date in Swift
I’d suggest to filter
and then sort
the array descending by the end date so the first item in the result is the latest entry. As first
is an optional unwrap it safely
if let latestEntry = data.filter{$0.eventType == 201}
.sorted{$0.endDateTime > $1.endDateTime}
.first { …
Swift 5 : Convert Array/Dictionary to JSON format
You can create a model and encode to it like;
let yourArray = [
(ingredient_item: "Oil", ingredient_item_id: "1", ingredient_qty: "1", ingredient_unit_id: "Tsp", ingredient_remark: ""),
(ingredient_item: "Saffron", ingredient_item_id: "2", ingredient_qty: "2", ingredient_unit_id: "Tsp", ingredient_remark: ""),
(ingredient_item: "Rice", ingredient_item_id: "3", ingredient_qty: "2", ingredient_unit_id: "Cup", ingredient_remark: "")
]
struct Model: Encodable {
var ingredient_item: String
var ingredient_item_id: String
var ingredient_qty: String
var ingredient_unit_id: String
var ingredient_remark: String
}
let arr = yourArray.map({ Model(ingredient_item: $0,
ingredient_item_id: $1,
ingredient_qty: $2,
ingredient_unit_id: $3,
ingredient_remark: $4)})
let jsonData = try! JSONEncoder().encode(arr)
let jsonString = String(data: jsonData, encoding: .utf8)
What does backslash do in Swift?
The backslash has a few different meanings in Swift, depending on the context. In your case, it means string interpolation:
print("The total cost of my meal is \(dictionary["pizza"]! + dictionary["ice cream"]!)")
...is the same as:
print("The total cost of my meal is " + String(dictionary["pizza"]! + dictionary["ice cream"]!))
But the first form is more readable. Another example:
print("Hello \(person.firstName). You are \(person.age) years old")
Which may print something like Hello John. You are 42 years old
. Much clearer than:
print("Hello " + person.firstName + ". You are " + String(person.age) + " years old")
Converting URL to String and back again
fileURLWithPath()
is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString
is a full URL string including the scheme, so you should use
let url = NSURL(string: urlstring)
to convert it back to NSURL
. Example:
let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt
Related Topics
Arrayliteralconvertible: Just a Normal Protocol
What Is The Default Value of The Padding Modifier in Swift
Scenekit - Why Scnlight Created Automatically in Scnscene
Event Scrolling (Scrollviewdidscroll) Never Called - Swift 3
Vapor 3 Postgresql Crud Without Requests Http
How to Change Font Size of Nstableheadercell
Loading Image from Assets to Nsimage Keep Getting Error, Expecting Nsimage.Name
How to Access The Model Component of Reality Composer in Realitykit
Is There a Way in Swiftui to Detect If a User Has Larger Text Size Enabled
How to Fix Cannot Find 'Firebaseapp' in Scope
Vapor 3 - How to Check for Similar Email Before Saving Object
Cannot Get Newpassword to Generate Strong Password and Autofill
iOS 10 App Crashes When Accessing Camera
Xcode Issue: Library Not Loaded: @Rpath/Libswiftappkit.Dylib