initialise a variable based on a condition in swift

You can use a conditional statement to initialize a variable in Swift. For example, you can check if a certain condition is true or false, and based on that, assign a value to a variable. Here's an example:

main.swift
var number: Int
if someCondition {
    number = 1
} else {
    number = 2
}
76 chars
7 lines

In this example, if someCondition is true, the variable number will be initialized to 1. Otherwise, it will be initialized to 2.

Alternatively, you can use a ternary operator to achieve the same result in a more concise way:

main.swift
let number = someCondition ? 1 : 2
35 chars
2 lines

This code initializes the variable number to 1 if someCondition is true, and to 2 if it is false.

gistlibby LogSnag