Swift Learning Documentation (notes) _swift

Source: Internet
Author: User
Tags constant documentation

Swift is a new programming language for iOS and OS X applications, based on C and objective-c, without some of the compatibility constraints of C. Swift uses a secure programming model and adds modern functionality to make programming simpler, more flexible, and more fun. The interface is based on the cocoa and cocoa touch framework, which is widely loved by people, and shows the new direction of software development.

Variables and constants

Variable definitions use VAR, constants use Let, type safety, there is automatic type deduction, note that the assigned = number must have spaces on both sides. Variables and constant names can be almost all characters, which are much like JavaScript. Chinese programming is a bit of a kick.

var a = 123//a for int
let B = "Helo"//b for string
var cat = "Meow"

Digital

    • Decimal
    • Binary system 0b101
    • Octal system 0o5
    • Hexadecimal 0x5

Longer numbers can be added to improve the readability of the program, such as 0_0 is actually 0,_ line can not be added to the beginning

Boolean type

True and False, when the process controls if, the judgment statement return must be a bool value, such as:

Let i = 1
if I {
 //Compile error
}

This will allow you to pass

if i = = 1 {
}

It's not like the automatic type conversion in JS.

Type Alias

Adding aliases to your current type can also improve the readability of your program, such as

Typealias Audio sample = UInt16

You can use the maximum amplitude that Var has discovered in other places = Audio sampling. Min

META Group

It can be a set of values that don't have to be the same type, for example, define myself:

var jserme = ("183cm", "num", "76kg")

Can be accessed like an array.

println (jserme.0)//back to 183cm

To restore a tuple to a separate variable or constant

Let Jserme = ("183cm", "num", "76kg") let
(height, age, weight) = Jserme
println ("Height is height")

You can also name each value (it's like making an array of objects in JS ...). )

Let Jserme = (height: "183cm", Age: 26, Weight: "76kg")
println ("Height is (jserme. height)")

String

String literals can only be defined with "", and string is essentially an ordered collection of character.

For char in "Shiyan" {
 println (char)
}/
 
*
a
word
both
out
* *

Literal amount and whether the judge is empty

var string = "I am the string"
var empty string = ""
 
if empty string. isempty {
 println ("This is an empty string")
}
 
if empty string = "" {
 println (" This is an empty string ")
}

The string instance has two methods Hasprefix and Hassuffix, such as:

var idiom array = [
 "Shiyan",
 "hair-trigger",
 "Toruk macto called",
 "a mallet tuning",
 "Nothing",
 "lifelong",
 "at first sight"
]
 
var count = 0 for
idiom in idiom array {
 if (idiom. Hasprefix ("one")) {
  count++
 }
}
 
println (count)/ /Output 7

Like JS, string is also a value reference, and the following two variables are modified without affecting each other

var a string = "I am the string one"
var two string = A string of
 
two strings = "I am the string two"
 
println ("string one: \ (a string), string two: \ (two strings)")

Interval operator

The closed interval uses a...b, from A to B, containing A and b, and half interval a. b, from A to B, does not contain B, for example:

An array of var idioms = [
 "Shiyan",
 "hair-trigger",
 "Toruk macto called"
] for i in 0.
 
an array of idioms. Count {
 println ("The"/(i) idiom is: \ ( idiom array [i]) "
}
//How to use here ... Will complain, because the idiom array [3] is not a value

Two kinds of sets, array and dictionaries

Relative to JS logarithmic group and the loose requirements of object members, Swift requires that the array and dictionaries member types must be consistent

var shopping list: string[] = ["egg", "milk"]
//can also be the following such
//var shopping list = ["Egg", "milk"]

The array can be modified using the Append method or + =

var shopping list = ["Eggs", "milk"]
 
shopping list. Append ("apple")
 
shopping list + + strawberry
 
println ("(Shopping list)")//[eggs, milk, apples, strawberries]

Array can be obtained by index or by the interval operator

var shopping list = ["Egg", "milk"]
 
println ("(shopping list [0])")//Egg
println ("(shopping list [0..1])")//[eggs]
println ("Shopping list [ 0...1]) "//[eggs, Milk]
println (" (shopping list [0...2]) "//[eggs, Milk,]

Definition of dictionaries

var airports:dictionary<string, string> = ["Tyo": "Tokyo", "DUB": "Dublin"]
 
//can also be reduced to
//var airports = [" Tyo ":" Tokyo "," DUB ":" Dublin "]

It is modified and read using [], and cannot be used.

airports["BJ"] = "Beijin"

Control statements

As shown in the previous examples, the condition of the control statement is not like JS with parentheses

for var index = 0; Index < 3; index++ {
 println (' index is \ (index) ')
}
//index is 0
//index are 1
//index is 2

Function

Declaration and invocation of functions:

Func SayHello (personname:string)-> String {let
 greeting = "Hello," + PersonName + "!"
 return greeting
}
 
println (SayHello ("Jserme"))

Returns a function that returns a void that is equivalent to an empty tuple ()

Functions with multiple return values and default parameters:

Func info (word:string = "aha")-> (Length:int, Containa:bool) {
 var Containa = False for
 char in Word {
  if ( char = = "a") {
   Containa = True break
  }
 } return
 
 (Word.utf16count, Containa)
}
 
println ( info (Word: "bobo")//(2, False)
println (info ())//(3, True)

An external parameter name that is easy to read, separated from the parameter definition by a space before the parameter definition, such as the following multiple parameters

Func Join (String s1:string, toString s2:string, Withjoiner joiner:string)
 -> string {return
 S1 + joiner + S2
}
 
//Call when
join (string: "Hello", toString: "World", Withjoiner: ",")
//returns "Hello, World"

The parameter name is the same as the external parameter name, and the parameter name can be added with the # ID:

Func Containscharacter (#string: String, #characterToFind: Character)-> Bool {for
 Character in string {
  if Cha Racter = = Charactertofind {return
   true}/Return
 false
} let
containsavee = Containscharacter (string: "Aardvark", Charactertofind: "V")
//Containsavee equals True, because "aardvark" Contains a "V"

The parameter of the function is a constant and cannot be modified, if modified in the function, the variable is defined before adding Var

Func AlignRight (Var string:string, Count:int, Pad:character)-> string {let
 Amounttopad = count-countelement S (string) for
 _ in 1...amountToPad {
  string = Pad + string
 } return
 string
 
originalstring = "Hello" let
paddedstring = AlignRight (originalstring, "-")
//PaddedString be equal to "--- --hello "
//originalstring is still equal to" hello "

If you want to modify an incoming parameter within a function, you can use the InOut keyword to identify that the incoming argument requires a prefix and the internal implementation should be a pointer.

Func swaptwoints (inout a:int, inout b:int) {let
 Temporarya = a
 a = b
 b = Temporarya
}
var someint = 3
var anotherint =
swaptwoints (&someint, &anotherint)
println ("Someint is Now" (Someint), and Anotherint is now (anotherint) ")
//prints" Someint are now, and Anotherint are now 3 "

function type, you can use functions as parameters and return values like JS

Func addtwoints (A:int, b:int)-> int {return
 a + b
}//function type (int, int)-> int
func multiplytwoints (a : int, b:int)-> int {return
 a * b
}//function type (int, int)-> int
 
//receive function type named Mathfunction
func Thresult (mathfunction: (int, int)-> Int, A:int, b:int) {
 println ("Result: \ (Mathfunction (A, b)")
}
PR Intmathresult (Addtwoints, 3, 5)
//prints "result:8"
 
//Return function type
func stepforward (input:int)-> Int { C14/>return input + 1
}
func Stepbackward (input:int)-> Int {return
 input-1
}
Func chooses Tepfunction (Backwards:bool)-> (int)-> int {return
 backwards? Stepbackward:stepforward
}
var cu  Rrentvalue = 3 let
Movenearertozero = choosestepfunction (CurrentValue > 0)
//Movenearertozero now refers to The Stepbackward () function

Closed Bag

A function is called a closure with a variable of the context it contains. such as the sort function:

Let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
 
func backwards (s1:string, s2:string)-> Bool {
 Retu RN S1 > S2
}
var reversed = sort (names, backwards)
println (Reversed)
//reversed is equal to ["Ewa", "D Aniella "," Chris "," Barry "," Alex "]s

Using closures can be expressed as:

Let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
 
var reversed = sort (names, {(s1:string, s2:string)-> Boo L in return
 S1 > S2
})
println (Reversed)
//reversed are equal to ["Ewa", "Daniella", "Chris", "Barr" Y "," Alex "]

can also be simplified to

Let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
 
var reversed = sort (names, {s1, s2 in S1 > s2})
 
println (Reversed)

Enumeration

Through the following syntax declaration

Enum Barcode {case
 upca (int, int, int.) = (1,2,3) case
 qrcode (String) = "Hello"
}

Class and struct body

It is recommended to use first letter capitalization to name

struct resolution {
 var width = 0
 var heigth = 0
}
class Videomode {
 var Resolution = Resolution () 
   var interlaced = False
 var framerate = 0.0
 var name:string?
}

To generate an instance:

Let Someresolution = Resolution () let
somevideomode = Videomode ()

Property access and modification, using. Syntax:

println ("The width of Somevideomode is \ (someVideoMode.resolution.width)")
SomeVideoMode.resolution.width = 12880
println ("The width of Somevideomode is now" (SomeVideoMode.resolution.width))

The structure body has an automatic member initializer, and the class instance does not:

Let VGA = Resolution (width:640, heigth:480)

Structs and enumerations are value types, and classes are reference types

For values that reference the same instance, you can use = = = and!== to judge

Deferred properties, @lazy, setting to initialize a specific property when called

Class Dataimporter {/
 *
 Dataimporter is a class that imports data from an external file.
 initialization of this class consumes a lot of time.
 * *
 var fileName = "Data.txt"
 //This is to provide data import function
}
 
class DataManager {
 @lazy var importer = Dataimporter ()
 var data = string[] ()
 //This is providing data management functionality
} let
 
manager = DataManager ()
Manager.data + = "Some data"
manager.data + = "Some more Data"
//Dataimporter The instance's importer attribute has not yet been created

Classes, structs, enumerations can be set by setting the setter and getter to

struct Alternativerect {
 var origin = point ()
 var size = size ()
 var center:point {get
 {let
  CenterX = origin.x + (SIZE.WIDTH/2) let
  centery = Origin.y + (SIZE.HEIGHT/2) return point
  (X:centerx, Y:centery)
 set {//Here setter does not define a parameter name that represents the new value, you can use the default name newvalue
  origin.x = newvalue.x-(SIZE.WIDTH/2)
  ORIGIN.Y = Newva Lue.y-(SIZE.HEIGHT/2)
 }}}

Read-only property removes get and set

Property monitoring can be handled using Willset and Didset

The type attribute is somewhat like a static variable, declared with the static keyword

struct Somestructure {
 static var storedtypeproperty = "Some value."
 static Var computedtypeproperty:int {
 //returns an INT value
 }
}

Subscript

Classes, structs, enumerations can have subscripts, and it has the like to add a shortcut to them, as follows:

struct Timestable {let
 multiplier:int
 subscript (index:int)-> Int {return
  multiplier * Index
 }
   
     let
threetimestable = timestable (multiplier:3)
println ("3 6 times Times is \ (Threetimestable[6])")
//Output "3 6 times times 18"

   

Inherited

Define a class

Class Vehicle {
 var numberofwheels:int
 var maxpassengers:int
 func description ()-> String {
  Return "\ (numberofwheels) wheels; Up to \ (maxpassengers) passengers "
 }
 init () {
  numberofwheels = 0
  maxpassengers = 1
 }
}

Inheriting classes

Class Bicycle:vehicle {
 init () {
  super.init ()
  numberofwheels = 2
 }
}

overriding Properties and methods

Class Car:vehicle {
 var speed:double = 0.0
 override var speed:double {get
 {return
  super.speed
 }
   set {
  super.speed = min (newvalue, 40.0)
 }
 }
 init () {
  super.init ()
  maxpassengers = 5
  numberofwheels = 4
 }
 Override func description ()-> String {return
  super.description () + ";"
   + "Traveling at \ (speed) mph"
 }
}

Prevent overrides, @final with keyword before method and property, error at compile time

Constructors

You can write multiple init in a statement, which is a bit like overloading

struct Celsius {
 var temperatureincelsius:double = 0.0
 init (Fromfahrenheit fahrenheit:double) {
  Temperatureincelsius = (fahrenheit-32.0)/1.8
 }
 init (Fromkelvin kelvin:double) {
  Temperatureincelsius = k elvin-273.15
 }
} let
 
boilingpointofwater = Celsius (fromfahrenheit:212.0)
// Boilingpointofwater.temperatureincelsius is 100.0 let
freezingpointofwater = Celsius (fromkelvin:273.15)
// Freezingpointofwater.temperatureincelsius is 0.0 "

The destructor of a class

There are some places called reverse initialization, very awkward names.

Class Player {
 var coinsinpurse:int
 init (coins:int) {
  coinsinpurse = bank.vendcoins (coins)
 }
 
 func wincoins (coins:int) {
  Coinsinpurse + = bank.vendcoins (coins)
 }
 
 deinit {
  Bank.receivecoins (coinsinpurse)
 }
}
 
var player = player (coins:200)
player = nil//Call Deinit method

Extended

For classes, structs, enumerations, you can extend all of their

Class player{
 var age:int
}
 
extension player{
 func repetitions (Task: ()-> ()) {for
  i 0..self {
   task ()}}}

Agreement

It's actually an interface description.

 Protocol Someprotocol {
  var mustbesettable:int {get Set}
  var doesnotneedtobesettable:int {get}
  func s Ometypemethod ()
 }

Protocol inheritance

 Protocol Inheritingprotocol:someprotocol, Anotherprotocol {
  //protocol definition goes here
 }

Generic type

The generic version of this function uses the name of the node type (usually represented by the letter T) in place of the actual type name (such as int, string, or double). The node type name does not mean that T must be of any type, but it stipulates that A and B must be the same type of T, regardless of whether t represents any type. Only the actual type that the Swaptwovalues function passes in each call determines the type that T represents.

 Func swaptwovalues<t> (inout a:t, inout b:t) {let
  Temporarya = a
  a = b
  b = Temporarya
 }

Operator overloading

This shows the overloaded + operator

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)
}
    • The front operator @prefix
    • The post operator @postfix
    • The combined assignment operator @assignment
    • comparison operator @infix
@prefix @assignment func + + (inout vector:vector2d)-> vector2d {
 vector + vector2d (x:1.0, y:1.0) return
 V Ector
}

Custom operators

The operator of individuality can only use these characters/=-+ *% < >! & | ^. ~

Operator prefix +++ {}
@prefix @assignment func +++ (inout vector:vector2d)-> vector2d {
 vector + vector
   return Vector
}

The value of the binding (associativity) defaults to None, available left,right,none, and priority (precedence) defaults to 100.

Operator infix +-{associativity left precedence 140}
func +-(left:vector2d, right:vector2d)-> vector2d {
   
    return vector2d (x:left.x + right.x, y:left.y-right.y)
} let-
firstvector = vector2d (x:1.0, y:2.0) let
se Condvector = vector2d (x:3.0, y:4.0) let
plusminusvector = firstvector +-secondvector
//Plusminusvector The value at this time is ( 4.0,-2.0)

   

From: http://jser.me

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.