user11303607
user11303607

Reputation:

Use of Separator while accessing arrays

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

Upvotes: 2

Views: 69

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15758

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

Upvotes: 1

Nathaniel
Nathaniel

Reputation: 70

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.

Upvotes: 0

Related Questions