2

I'm learning Swift through Youtube using online compilers on Windows and while learning to access arrays, I experienced that I had to use "," as separator in place of "\" inside the print function. But "\" was used in the video I was watching (she was using Xcode on Mac). What's the reason behind this? I've provided the code below.

import Foundation

let friends = ["Alisa", "Alice", "Joseph"]
print("friend 1: " ,(friends[1]))
4
  • Show the code you saw in the video. Commented Apr 3, 2019 at 6:27
  • Interesting question, I have never seen the use of comma before. And why no comma when I do for i in 0..<friends.count { print("friend \(i): \(friends[i])") }? Commented Apr 3, 2019 at 6:48
  • 1
    hey I've got the answer. if we use the declared variable or constant within the double quotes, then we separate them with "\" and if we use it outside the double quotes then we have to separate them with ",". Commented Apr 3, 2019 at 9:39
  • @Sappie You wrap the variable or constant in \(), not just \. The print line in your question doesn't need the () around friends[1]. Commented Apr 3, 2019 at 15:31

2 Answers 2

1

In String Interpolation each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash \(var)

let friends = ["Alisa", "Alice", "Joseph"]
print("friend 1: \(friends[0])")

Or you can create a string with Format Specifiers

print(String(format:"friend 2: %@", friends[0]))

print statement accepts a list of Any objects. In the below line both objects are separated by comma

print("friend 1: " ,(friends[1]))//friend 1: Alice
print(1,2,3)//1 2 3
Sign up to request clarification or add additional context in comments.

Comments

0

The technique is String Interpolation. You construct a new string from string literals.

let name = "Bob"
//Returns: Hi Bob"
print("Hi \(name)")

Read more at: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292

A string literal is a predefined string value.

//This is a string literal.
let name = "Bob"

You can still use array values with String Interpolation.

let friends = ["Alisa", "Alice", "Joseph"]
let friend1 = friends[1]

print("friend 1: \(friend1)")
print("friend 1: \(friends[1])")
//These 2 print methods return same value.
//One is a constant, one is an array element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.