Swift Introduction | Values, Variables, and Operations | Additional Basics

This article introduces additional concepts related to values, variables, and operations.

Separating Statements with Newlines or Semicolons

Swift statements are usually separated by line breaks. To write multiple statements on one line, separate them with semicolons (;).

a = 1; b = 2; c = 3

Comments with // or /* */

Swift supports two comment styles. Text after // is treated as a comment until the end of the line. Text between /* and */ is also treated as a comment.

Block comments can be nested.

/* comment is /* THIS! */ text. */

Grouping Variable Declarations and Assignments

When declaring several variables, it can be convenient to write them together.

var (variable1, variable2, ...) = (value1, value2, ...)

The values are assigned in order: value1 to variable1, value2 to variable2, and so on.

Preventing Overflow with &

When working with large numbers, pay attention to overflow and underflow. Overflow occurs when an integer exceeds the range supported by its type. Underflow occurs when a floating-point value falls outside its representable precision. Other calculation errors include division by zero.

When you intentionally want wrapping behavior instead of an error, add & to the operator.

var x = y & + 100000

Casting Values

Swift values have static types. To calculate with values of different types, cast one value to the other type with Type(value).

// Convert to an integer
123 + Int(45.67)
// Convert to text
"123"+ String(456)

These concepts cover the basics of values, variables, and operations. The next topic is control statements, a core part of programming syntax.