swift learning document of notes
- 2020-05-06 11:44:03
- OfStack
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 secure programming modes and adds modern functionality to make programming easier, more flexible, and more fun. The interface, based on the popular Cocoa and Cocoa Touch frameworks, shows a new direction for software development.
Variables and constants
var for variable definitions, let for constants, type safe, with automatic type derivation, note that there must be Spaces on both sides of the = sign. Variable and constant names are available for almost all characters, which are very much like javascript. Chinese programming is awesome.
var a = 123 //a for Int
let b = "helo" //b for String
var meow = " meow "
Digital
Decimal binary 0b101 octal 0o5 hexadecimal 0x5Long Numbers can be added to improve the readability of the program. For example, 0_0 is 0, and the _ line cannot be added at the beginning of
Boolean type
When true and false process control if, the return must be an Bool value, such as
let i = 1
if i {
// A compiler error
}
So you can go through
if i == 1 {
}
It's not like js which has an automatic type conversion
Type alias
Adding aliases to existing types, such as
, also makes the program more readable
typealias Audio sampling = UInt16
You can use the maximum amplitude var has found elsewhere = audio sample.min
Tuples
It can be a set of values that do not have to be of the same type, for example, define myself:
var jserme = ("183cm", 26, "76kg")
You can access
like an array
println(jserme.0) // return 183cm
The tuple is restored to a separate variable or constant,
let jserme = ("183cm",26,"76kg")
let ( height , age , weight ) = jserme
println(" Height is \( height )")
You can also name each value (this is like making an array an object in JS...)
let jserme = ( height :"183cm", age :26, weight :"76kg")
println(" Height is \(jserme. height )")
String
String literals can only be defined as "", String is essentially an ordered set of Character.
for char in " A word spoken "{
println(char)
}
/*
one
said
both
Out of the
*/
The literal and whether the judgment is empty
var string = " I'm a string "
var An empty string = ""
if An empty string .isEmpty {
println(" This is an empty string ")
}
if An empty string == "" {
println(" This is an empty string ")
}
String instances have two methods hasPrefix and hasSuffix, such as
let i = 1
if i {
// A compiler error
}
0
Like js, string is a pass-through reference, and changes to the following two variables do not affect each other
var A string of = " I'm string one "
var Second string = A string of
Second string = " I'm string two "
println(" A string :\( A string of ) . String two :\( Second string )")
The interval operator
Closed interval using a... b, from a to b, including a and b, half interval a.. b, from a to b, does not contain b, e.g.
var Idioms array = [
" A word spoken ",
" explosive ",
" Resonate with many "
]
for i in 0.. Idioms array .count {
println(" The first \(i) A proverb is :\( Idioms array [i])")
}
// How to use it here ... It will report an error because of the array of idioms [3] There is no value
Two sets,array and dictionaries
swift requires that the array and dictionaries member types be the same as
, whereas js requires that the array and dictionaries member types be the same as
let i = 1
if i {
// A compiler error
}
3
The array can be modified using the append method or +=
let i = 1
if i {
// A compiler error
}
4
The array can be obtained either by index or by the interval operator
let i = 1
if i {
// A compiler error
}
5
dictionaries definition
let i = 1
if i {
// A compiler error
}
6
It is modified with a read using [] instead of.
let i = 1
if i {
// A compiler error
}
7
Control statement
As shown in the previous examples, the condition of the control statement does not have the parentheses
of js
let i = 1
if i {
// A compiler error
}
8
Function
Function declaration and invocation:
let i = 1
if i {
// A compiler error
}
9
The no-return function essentially returns an Void, which is equivalent to an empty tuple ()
Multi-return value function with default parameter:
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 easy to read external parameter name separated from the parameter definition by a space before the parameter definition,
for the following parameters
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}
// When called
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 identified by # :
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
for character in string {
if character == 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 constant and cannot be modified. If the parameter is modified within the function, var
is added before the variable definition
func alignRight(var string: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(string)
for _ in 1...amountToPad {
string = pad + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"
If you want to modify the parameters passed in the function, you can use the inout keyword to identify the parameters passed in.
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"
Function type, can use function as parameter and return value
like js
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
} // The function type is (Int, Int) -> Int
func multiplyTwoInts(a: Int, b: Int) -> Int {
return a * b
}// The function type is (Int, Int) -> Int
// To receive, mathFunction Function type of
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"
// Return function type
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
Closure
A function with variables in the context it contains is called a closure. For example, sort function :
if i == 1 {
}
6
Using closures can be expressed as :
if i == 1 {
}
7
It can also be simplified to
if i == 1 {
}
8
Enumeration
Declare
through the syntax below
if i == 1 {
}
9
Class and struct
It is recommended to name
with its first capital letter
struct Resolution {
var width = 0
var heigth = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
Generate instance:
typealias Audio sampling = UInt16
1
Property access and modification, using. Syntax:
typealias Audio sampling = UInt16
2
Structs have automatic member initializers, class instances do not:
typealias Audio sampling = UInt16
3
Structs and enumerations are value types, and classes are reference types
For values that reference the same instance, use === and! == to judge
The delay property, @lazy, is set to initialize the specific property
only when invoked
typealias Audio sampling = UInt16
4
Classes, structs, and enumerations can all be
by setting setter and getter
typealias Audio sampling = UInt16
5
Read - only attribute removed get and set
Property monitoring can handle
using willset and didsetA type property is somewhat like a static variable, declaring
with the static keyword
typealias Audio sampling = UInt16
6
The subscript
Classes, structures, and enumerations can all have subscripts, and it adds a shortcut to them as follows:
typealias Audio sampling = UInt16
7
Inheritance
Define a class
typealias Audio sampling = UInt16
8
Derived classes
class Bicycle: Vehicle {
init() {
super.init()
numberOfWheels = 2
}
}
Override property and method
var jserme = ("183cm", 26, "76kg")
0
To prevent overwriting, prefix methods and properties with the keyword @final, which causes errors in compilation
Constructor
You can write multiple init in the declaration, which is a bit like overloading
var jserme = ("183cm", 26, "76kg")
1
Class destructor
Some places are called uninitializers, awkward names,
var jserme = ("183cm", 26, "76kg")
2
Extension
For classes, structs, and enumerations, you can extend all of
var jserme = ("183cm", 26, "76kg")
3
Agreement
The interface description is
var jserme = ("183cm", 26, "76kg")
4
Protocol inheritance
var jserme = ("183cm", 26, "76kg")
5
Generic
The generic version of this function USES the node type name (usually represented by the letter T in this case) instead of the actual type name (such as Int, String, or Double). The node type name does not mean that T must be any type, but it states that a and b must be T of the same type, regardless of whether T represents any type. Only the actual type passed in at each invocation of the swapTwoValues function determines what type T represents.
var jserme = ("183cm", 26, "76kg")
6
Operator overloading
This example demonstrates the overloading + operator
var jserme = ("183cm", 26, "76kg")
7
The leading operator @prefix the following operator @postfix the combined assignment operator @assignment the comparison operator @infix
var jserme = ("183cm", 26, "76kg")
8
Custom operator
The character operators can only use these characters / = - + * % < > ! & | ^. ~
var jserme = ("183cm", 26, "76kg")
9
The value of associativity (associativity) defaults to none, left,right,none are available, and the priority (precedence) defaults to 100.
println(jserme.0) // return 183cm
0
From: http: / / jser me