Swift Cheat Sheet

Source: Internet
Author: User

Swift's some quick look-up tables, reproduced, but paste the code when the line is a problem, this How to solve?

Do not like the format can see the original: http://codeinswift.com/swift-cheat-sheet/


Basics
println ("Hello, World") var myvariable =//variable (can ' t is nil) letπ= 3.1415926//constant Let (x, y) = (10, 20)  x = ten, y = explicitdouble:double = 1_000.000_1//1,000.0001 Let label = "some text" + String (myvariable)// Casting Let Pitext = "Pi = \ (π)"//String interpolation var optionalstring:string? = "Optional"//can be nil optionalstring = nil/Do you know/* you Can nest Multiline comments */? */

Arrays
 array var shoppinglist = ["Catfish",  "water",  "lemons"]shoppingList[1]  =  "Bottle of water"  // update shoppinglist.count // size of  array  (3)  shoppinglist.append ("Eggs") shoppinglist +=  "Milk"  // Array  Slicing var fiblist = [0, 1, 1, 2, 3, 5, 8, 13, 21 ,  34, 5]fiblist[4..6] // [3, 5]. note: the end range value  is exclusive fiblist[0..fiblist.endindex] // all except last item  // Subscripting returns the Slice type, instead of the  Array type. // you may need to cast it to array in  order to satisfy the type checker array (fibList[0..4])  //  Variants of creating&nbSp;an array. all three are equivalent. var emptyarray1 = string[] ()  var emptyarray2: string[] = [] var emptyarray3: string[] =  string[] ()

Dictionaries
Dictionary var occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic"]occupations["Jayne"] = "public Relations" VA R 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 one!")}}  // for loop  (dictionary)  var dict = [  "name":  "steve  Jobs ", " title ": " CEO ", " Company ": " Apple " ] for  (key, value)  in  dict {println ("\ (key):  \ (value)")} // for loop  (range)  for 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 loop var i = 1 while i < 1000 {i *=  2 } // do-while loop do {println ("Hello")} while 1 ==  2 // switch let vegetable =  "Red pepper"  switch vegetable {  case  "Celery": let vegetablecomment =  "Add some raisins and  make ants on a log. "  case  "cucumber",  "watercress": let vegetablecomment =  "that 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 content let 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 string func greet (name: String, day:  string)  -> String { return  "hello \ (name),  today is \ ( Day). "  }greet ("Bob",  "Tuesday")  // call the greet function // function  that returns multiple items in a tuple func getgasprices ()   ->  (double, double, double)  { return  (3.59, 3.69, 3.79)} //  Function that takes variable number of arguments, collecting  Them into an array func setup (Numbers: int ...)  { // do something }setup (5, 16, 38)  // call the setup  function with array of inputs // Nested functions can  organize code that is long or&Nbsp;complex func printwelcomemessage ()  -> String { var y =  " Hello, " func add ()  {y += "  world " }add ()  return y} Printwelcomemessage ()  // Hello world // Passing and returning  Functions func 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 '  separates the closure header from the closure  body var numbers = [1, 2, 3, 4, 5]numbers.map ({(number: Int )  -> int in let result = 3 * number return result})  // When the type is known, like above, we can do  This numbers = [1, 2, 6]numbers = numbers.map ({ number in 3 &NBSP;*&NBSP;NUMBER&NBSP, println (numbers)  // [3, 6, 18] // When a  Closure is the last argument, you can place it after the  )  // when a closure is the only argument, you can  omit the ()  entirely // you can also refer to closure arguments by  position  ($0, $1,&nbsp, ...)  rather than name numbers = [2, 5, 1]numbers.map { 3 * &NBSP;$0&NBSP;}&NBSP;//&NBSP;[6,&NBSP;15,&NBSP;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 Perimeter:int {get {return 4 * sidelength}set {sidelength = Newvalue/4}}init (si  Delength:int) {self.sidelength = Sidelengthsuper.init ()}func shrink () {if sidelength > 0 {--sidelength}}override func Getarea (), Int {return sidelength * sidelength}

} var mysquare = Square (sidelength:5) print (Mysquare.getarea ())//Mysquare.shrink () print (mysquare.sidelength)//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) {println ("about To set Totalsteps to (Newtotalsteps)} didset {if totalsteps > OldValue {println ("Added (totalsteps–oldvalue) St EPS to ' Totalsteps ')}}} var stepcounter = Stepcounter () Stepcounter.totalsteps = +//About to set Totalsteps to 1 XX \ Added steps to ' totalsteps ' stepcounter.totalsteps = 145//About to set Totalsteps to 145 \ r Added ' Totalsteps '

If you don ' t need a custom getter and setter, but still want to run code//before an after getting or setting a proper Ty, 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 self} {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 an already created type

Adds the methods first and rest to the array type extension array {func 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 has to add @assignment 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 the 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 where after thetype 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 where and simply write the protocol or class name after a colon. Writing <T:Sequence> is the 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 Cheat Sheet

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.