http://codeinswift.com/swift-cheat-sheet/
http://my.oschina.net/ioslighter/blog/361229
Basics
println ("Hello, World") var myvariable = A//variable (can ' t be nil) letπ= 3.1415926 //Constantlet (x, y) = (10 , +) //x = ten, y = 20let explicitdouble:double = 1_000.000_1 //1,000.0001let label = "some text" + String (MyV ariable) //Castinglet Pitext = "Pi = \ (π)" //String interpolationvar optionalstring:string? = "Optional" // can be niloptionalstring = nil/* do you know/* You can nest multiline comments * *? */
Arrays
Arrayvar shoppinglist = ["Catfish", "water", "lemons"]shoppinglist[1] = "Bottle of Water" //updateshoppinglist.co UNT //Size of Array (3) shoppinglist.append ("eggs") shoppinglist + = "Milk"//array Slicingvar fiblist = [0, 1, 1, 2, 3, 5, 8, 5]fiblist[4..6]//[3, 5]. Note:the End range value is exclusivefiblist[0..fiblist.endindex]//All except last item//subscripting returns the Slic E type, instead of the array type.//you could need to cast it to an array in order to satisfy the type Checkerarray (fiblist[0. .4])//variants of creating an array. All three is equivalent.var emptyArray1 = string[] () var emptyarray2:string[] = []var emptyArray3 = string[] () var Emptyar Ray4 = [String] ()
Dictionaries
Dictionaryvar occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic"]occupations["Jayne"] = "public Relations" Var Emptydictionary = dictionary<string, float> ()
Control Flow
For loop (array) Let MyArray = [1, 1, 2, 3, 5]for value in MyArray {if value = = 1 {println ("one!")} else {println ("not O ne! ")}} for (Index,value) in enumerate (MyArray) {println ("item\ (index + 1): \ (value)")}//for Loop (dictionary) var dict = ["Name": "Steve Jobs", "title": "CEO", "Company": "Apple"]for (key, value) in Dict {println ("\ (key): \ (value)")}//for Loop (range) fo R I in-1...1 {//[-1, 0, 1]println (i)}//use: To exclude the last number//for loop (ignoring the current value of the range on each iteration of the loop) for _ in 1 ... 3 {//do something three times.} While Loopvar i = 1while I < $ {i *= 2}//do-while loopdo {println ("Hello")} while 1 = = 2//Switchlet vegetable = ' Red pepper ' switch vegetable {case ' celery ': let vegetablecomment = ' Add some raisins and make ants on a log. ' Case ' cucumber ', ' watercress ': let vegetablecomment = ' would make a good tea sandwich. ' Case Let X where X.hassuffix ("Pepper"): let Vegetablecomment = "is it a spicy \ (x)?" Default://RequiRed (in order to cover all possible input) let vegetablecomment = "everything tastes good in soup."} Switch to validate plist contentlet city:dictionary<string, anyobject> = ["Name": "Qingdao", "Population": 2_721 _000, "abbr": "QD"]switch (city["name"], city["population"], city["abbr"]) {case (. Some (let CityName as NSString),. Some (let pop as NSNumber),. Some (let abbr as NSString)) where abbr.length = = 2:println ("City Name: \ (cityname) | Abbr.:\ (abbr) Population: \ (POP) ") default:println (" Not a valid city ")}
Functions
Functions is a first-class type, meaning they can be nested in Functions and can be passed around
Function that returns a Stringfunc greet (name:string, day:string), String {return ' Hello \ (name), today is \ (Day )."} Greet ("Bob", "Tuesday")//Call the greet function//function, this returns multiple items in a tuplefunc getgasprices ()-& Gt (double, double, double) {return (3.59, 3.69, 3.79)}//Function that takes variable number of arguments, collecting them to an Arrayfunc setup (nu Mbers:int ...) {//Do Something}setup (5, +)//Call the Setup function with array of inputs//Nested functions can organize code tha T is long or complexfunc printwelcomemessage (), String {var y = "Hello," func Add () {y + = "World"}add () return Y}print Welcomemessage ()//Hello world//passing and returning Functionsfunc Makeincrementer () (int, int) {func AddOne (Number:int), Int {return 1 + number}return Addone}var increment = Makeincrementer () increment (7)
Closures
Functions is special case closures ({})//Closure example.//', ' separates the arguments and return type//' in ' Separ Ates the closure header from the closure bodyvar numbers = [1, 2, 3, 4, 5]numbers.map ({(number:int)-Int Inlet Resul t = 3 * numberreturn result}//When the type was known, like above, we can do thisnumbers = [1, 2, 6]numbers = Numbers.map ({number in 3 * number}) println (numbers)//[3, 6, 18]//when a closure was the last argument, where can place it after the //When a closure are the only argument, you can omit the () entirely//you can also refer to closure arguments by Positi On ($, $, ...) rather than namenumbers = [2, 5, 1]numbers.map {3 * $}//[6, 15, 3]
Classes
All methods and properties of a class is public. If you just need to store data in a structured object, you should use a struct "' JS//A parent class of Square class Shape {init () {}func Getarea (), Int {return 0;}} A Simple class Square extends Shape class Square:shape {var sidelength:int//Custom getter and setter Propertyvar PE Rimeter:int {get {return 4 * sidelength}set {sidelength = Newvalue/4}}init (sidelength:int) {self.sidelength = SideLeng Thsuper.init ()}func shrink () {if sidelength > 0 {--sidelength}}override func getarea ()-Int {return sidelength * s Idelength}} var mysquare = Square (sidelength:5) print (Mysquare.getarea ())//Mysquare.shrink () print (Mysquare.sidele Ngth)//4//Access The Square class object,//equivalent to [square class] in objective-c. Square.self//example for ' willset ' and ' Didset ' class Stepcounter {var totalsteps:int = 0 {willset (newtotalsteps) {pri Ntln ("About to set Totalsteps to (Newtotalsteps)")} didset {if totalsteps > OldValue {println ("Added (totalsteps–oldvalue) steps to ' Totalsteps '")}}}} var stepcounter = Stepcounter () St Epcounter.totalsteps = +//about-set totalsteps to [Added] steps to ' totalsteps ' stepcounter.totalsteps = 1 Totalsteps to 145 \ Added steps to ' totalsteps '//If you don ' t need a custom getter and setter, but Still want to run code//before an after getting or setting a property, you can use Willset and Didset
Enums
Enums can optionally is of a specific type or on their own. They can contain methods like Classes.enum Suit {case spades, Hearts, Diamonds, Clubsfunc GetIcon () String {switch S Elf {case. Spades:return "?" Case. Hearts:return "?" Case. Diamonds:return "?" Case. Clubs:return "?"}}}
Protocols
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of Func Tionality.
Protocol Someprotocol {//Protocol definition goes here}
Extensions
ADD extra functionality to a already created type//adds the methods first and rest to the array typeextension array {fun C First (), any? {return Self[0]}func rest (), Array {if Self.count >= 1 {return Array (Self[1..self.endindex])} else {return []}}}
Operator overloading
You can overwrite existing operators or define new operators for existing or custom types.
// Overwrite existing types@infix func + (a: Int, b: Int) -> Int {return a - b}var x = 5 + 4 // x is 1
You can ' t overwrite the = operator
ADD Operators for new types
struct Vector2D {var x = 0.0, y = 0.0}@infix func + (left: Vector2D, right: Vector2D) -> Vector2D {return Vector2D(x: left.x + right.x, y: left.y + right.y)}
Operators can be prefix
, infix
, or postfix
.
You @assignment
has to add if you wish to define compound assignment operators like + =, + + or-=
@assignment func += (inout left: Vector2D, right: Vector2D) {left = left + right}
Operator overloading is limited to the following symbols:/=–+ *% < >! & | ^ . ~
Generics
Generic code enables you to the write flexible, reusable functions and types that can work with any type.
// Generic function, which swaps two any values.func swapTwoValues<T>(inout a: T, inout b: T) {let temporaryA = aa = bb = temporaryA}
// Generic collection type called `Stack`.struct Stack<T> {var elements = T[]()mutating func push(element: T) {elements.append(element)}mutating func pop() -> T {return elements.removeLast()}}
We can use certain type constraints in the types with generic functions and generic types. Use after the where
type name to specify a list of requirements.
// Generic function, which checks that the sequence contains a specified value.func containsValue<T where T: Sequence, T.GeneratorType.Element: Equatable>(sequence: T, valueToFind: T.GeneratorType.Element) -> Bool {for value in sequence {if value == valueToFind {return true}}return false}
In the simple cases, you can omit and where
simply write the protocol or class name after a colon. Writing is the <T: Sequence>
same as Writing <T where T: Sequence>
.
Emoji/unicode Support
You can use any of the Unicode character (including emoji) as variable names or in Strings.
Which, in Xcode looks like
Swift Quick Check form reproduced