Demo entry 2716738

CheatsheetSwift

   

Submitted by anonymous on Sep 21, 2015 at 03:17
Language: Swift. Code size: 2.6 kB.

///#The Swift Programming Language
///##*The Complete Cheatsheet*
///
///##**The Basics**
///
///###**Comments**

// this is a single-line comment

/* this is another comment,
   written over multiple lines */

/* this is the start of the first multiline comment
/* this is the second, nested multiline comment - usually commented code */
this is the end of the first multiline comment */

///###**Constants and variables**

// Declarations with Type Inferrence
let maxGrade = 10 // a constant initialized to an integer value of 10
var currentLevel = 0 // a variable initialized to integer 0
let capital = "Bucharest" // string constant
var name = "John Doe" // string variable
// notice the lack of ; at the end of line

let x = 0.0, y = 0.0, z = 0.0 // multiple constant declarations
var x = 0.0, y = 0.0, z = 0.0 // multiple variable declarations

// Declarations with Type Annotations
var welcomeMessage: String // a string variable
welcomeMessage = "Hello"
var otherVar:Int = 2 // annotated and initialized var
var red, green, blue: Double // mutiple variable declarations of the same type

// Constants and variables cannot change their kind once declared (they remain constants or variables for the rest of the program)

// Changing values
var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
// friendlyWelcome is now "Bonjour!"

let languageName = "Swift"
languageName = "Swift++"
// this is a compile-time error - languageName cannot be changed (because it was declared as a constant)

// Naming constants and variables
// both the identifiers and values can contain Unicode characters
let π = 3.14159
let 你好 = "你好世界"
let 🐶🐮 = "dogcow"

/* Enclose Swift language keywords with ` 
when used as constant or variable names (not recommended practice) */
let `let` = "constant"
let `if` = "for keyword"
var `var` = "variable"
var `for`: Int = 1

// Printing constants and variables
print(friendlyWelcome)
// prints "Bonjour!" and adds a newline character at the end
print(friendlyWelcome)
// as above but without the newline character

print("This is a string")
// prints "This is a string"

var v = 123
print(v) // prints 123

// String interpolation
// use \(varName) within strings
print("The current value of friendlyWelcome is \(friendlyWelcome)")
// prints "The current value of friendlyWelcome is Bonjour!"

// Semicolons
// used to delimit statements and expressions on a single line
let cat = "MyCat"; print(cat)
// prints MyCat
// otherwise is optional
let a = 1; // ; can be removed

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).