SLN
SLN

Reputation: 5082

emoji cannot be a literal and what else?

A literal is the source code representation of a value of a type, such as a number or string

There are 3 kinds of literals in Swift: Integer Literals, Floating-Point Literals and String Literals (please correct me if I'm wrong), Is that means (My Guess) any elements which not belong to a type of Integer, Floating or String is not considered as a literal, and will trigger an error when used as literals

According to what I guess I've tried this let aEmoji = 😀

enter image description here

Question1: Is my guess accurate? If not, I appreciate you could correct me.

Question2: Is there anything else shouldn't use as a literal? (would be nice you could give me some example)

Thanks

Upvotes: 0

Views: 633

Answers (3)

Alexander
Alexander

Reputation: 63271

  1. Yes, anything that isn't an integer literal (1), floating-point literal (1.0) or String literal ("foo"), Array literal ([foo]), Dictionary literal ([foo : bar]), bool literal (true/false) isn't a literal and would cause an error.

  2. Anything that isn't one of the literals above isn't a literal, and could cause an error (if it's an invalid syntax).

You can make put an emoji in a string literal, however: let aEmoji = "😀"

Upvotes: 3

cpimhoff
cpimhoff

Reputation: 675

You can include emojis in a literal String or Character expression by setting it off with double quotes.

The type inferrer will default the expression to a String literal, unless the Character type is specified.

let unicornString = "🦄"
let unicornChar : Character = "🦄"

Else the compiler will treat the emoji (or any unicode character sequence) as an identifier (because emoji can be variable names and such).


The following would be valid:

let 🔑 = "myPassword"
user.authenticateWithPassword(🔑)

Upvotes: 3

vadian
vadian

Reputation: 285072

A string literal is wrapped in double quotes

let aEmoji = "😀"

From the documentation:

A string literal is a fixed sequence of textual characters
surrounded by a pair of double quotes ("").

Upvotes: 4

Related Questions