Record: Swift Learning note 0-1

Source: Internet
Author: User

Swift is also constantly updated to make minor adjustments, saying that early birds have worms to eat, so we start early, while the vast majority of the domestic coder have not yet begun widespread application.

Some great gods on the internet say: Swift is simple! I disagree with this view, if you use Helloword to say that it is grammatically correct, but this simple example does not prove that it is simple in function!

I believe the swift language is very powerful and has a lot of super-powerful object-oriented features that OC didn't have before! It's not easy to use well!

Here are: Compare the system to organize their own study of Swift notes, on the one hand as a record, easy to consult later, but also to share to the needs of friends!

I am Ninhaire, mutual encouragement! I am challenging swift with you and many of my friends who have dreams!

First, Introduction

Objective-c more than 30 years of language, square brackets syntax, scare a lot of people.

Swift is a concise, powerful language that draws on the Javescript, Go language, powerful language, supports both functional programming, object-oriented programming, support functions and closures, value passing, and reference passing.

Supports object-oriented encapsulation, inheritance, polymorphic basic functions, also supports enumeration, struct, class three object-oriented types, create instances, invoke methods, allow to define attributes, methods, constructors, subscripts, nested types.

It's not easy to really master all of Swift's features.

Reference: The Swift Programming Language Programming Guide

Four parts:

1, development environment, playground function and usage, terminal compiling, running program;

2, basic grammar + functional programming +string\array/dictionary and other built-in types

3. Object-oriented Programming +foundation framework

4. MVC Design +ui Control

Just do It

Swift language is a strongly typed language, has very strict type checking, is a compiled language, compiled will get the executable target file.

Do not allow executable code to be placed in the class definition

For example:

Class test{

println ("Hello")

}

Framework: A set of functions, classes, and other program units that systematically provide a function of one aspect.

TERMINAL:SWIFTC command compiler Swiftc-o hello.out Helloworld.swift

Generate Hello.out File

./hello.out execution

Func Test () {

println ("Test function")

}

Swiftc-o test.out Test.swift Main.swift

In order for the system to find the Swift Compile command, the configuration path is added to the system's path

Modify the. bash_profile file implementation in the home directory (hide the file, go to home, and then Ls-a)

PATH =/applications/xcode-beta.app/contents/developer/toolchains/xcodedefault.xctoolchain/usr/bin: $PATH

: Is the delimiter between two paths

Reboot the system to

The Use core Date check box indicates that the project intends to access the SQLite database using core date

Test Case:

SetUp () initializes the underlying test resource

TearDown () Destroys test resources for setup () initialization

Wrap Lines Wrap Line

In the Help document: C is the class, M is the method, the PR is the protocol, and F is the function

II. Basic data types

Note: The code is a document.

var variable: A small container that is loaded with data,

var name = "Ninhaire"

Printlin (name)

Let constants: Once created cannot be changed

var lastname= "Ren"

Allname = LastName + "Hairui"

var str = "Heri" To determine if Sting is empty Str.isempty

Curly braces: {code block} includes: class, struct, enumeration, function body, method body

Square brackets: [array element or dictionary element] a[] = 3; cross["Swift"] = 80//Assign a value to the element in the cross dictionary that is key Swift

Parentheses (defining tuples or defining functions)

Polka dots. A class, struct, enumeration, instance, and its members (properties and methods) are called

Keywords: keyword with special-purpose words

Statement: Class,deinit,enum,extension,func,import,init,internal,let,operator,private,protocol,public,static,struct, Subscript,typealias,var

Statement: Break,case,continue,default,do,else,fallthrough,for,if,in,return,switch,where,while

Type, expression: As,dynamictype,false,is,nil,self,self,super,true,_column_,_file_,_function_,_line_

Multiple variables can be declared at the same time, different types

var a = 10,b:string,c = "Renhairui"

Let MyName = "Renhairui", MyAge = "26"

println () wraps after print () output content

String interpolation: The variable name/constant name is enclosed in parentheses and is previously escaped with a backslash. For example: println ("My name is: \ (myName), my age is: \ (myAge)")

Generally use the int type as much as possible, it will improve the generality, can access the min of different integral type, Max property to get the minimum maximum value , for example: println (int32.min)

Avoid using unsigned integers to improve code reusability and avoid changing values between different numeric types.

And suggest to change from small to large int8->int16->int32->int64->float->double

Bool can only be completely different in true,false and OC

tuple tuples: Use parentheses to combine multiple values into a single composite value, which can be any type.

var health = (180,70, "good")//Auto-inferred type (int,int,string)

You can nest Var test (+, "swift") with subscript access, \ (health.0) \ (test.1.0)

can also be split into a single var (height,weight,status) = health; println ("Height is: \ (height), Weight: \ (weight), status: \ (Status)")

Do not need some time, can use _ Underline, ignore let (a,b,_) = Health

Can be named with key value , var health = (height:180, Weight: 70,status ' good ")

When key is assigned, the order can be swapped. Access by name: \ (health.height)

What type of case is the optional type handling value missing? Sting?

var str = "Renhairui"

var num:int? = Str.toint ()//conversion failed, nil, value missing

Difference: Nil in OC represents a non-existent object pointer, which is completely different in Swift!

Only variable constants of an optional type can accept nil

var age:int = nil//Wrong!

Force parse forced unwrapping in order to get the value of the optional type, add it after the name! , parsing, indicating: Known value, extract value

var str:string? = "Renhairui"

var s:string = st!

var n1:int? = 10

var n2:int? = 5

Let sum = n1!+n2! Forced parsing must be used, otherwise compilation cannot pass

To ensure that forced parsing does not cause a run crash, provide if judgment

If str! = Nil

{

var s = str!

}else{

println ("Cannot force parsing")

}

If N1!=nil && n2!=nil{

Let sum = n1! +n2!

}

Optional binding optional binding is used to determine whether an optional type has a value, which is used in the IF while

var str:string? = "Renhairui"

If var tmp = str{
println (TMP)

}

implicitly optional type any existing type behind add! Represents an optional type
Difference:

Int! Accept int values and nil

int can only accept int values

int and Nil accepted but forced to parse

Function: Used to define variables that are not re-converted to nil after assignment

You also need to determine if let temp = name {}

type alias typealias typealias Counter = INT//After use Counter completely represents Int \ (Counter.max)

Unicode form \u{2666} represents ♦?

var str = string ()//Create an empty string

var strcopy = String (Count:5,repeatedvalue:character ("F"))//create 5 repeat F

Let name = "Renhairui"

var info = name + "is a good man!"

println (Info)

var subStr = name. Substringwithrange (Nsmakerange (3,6))//starting from 3, 6 consecutive, output Hairui

Swift's sting is a value type, a copy of the copy instance is passed, not OC's *

Info. RemoveAll //emptying

countelements (info)//Calculate the number of characters, Unicode can also

Traverse

For a in Info

{
println (a)

}

Compare strings: equals: = =, prefix equal:hasprefix (), suffix equal:hassuffix ()

var hasorno:bool = name.hasprefix ("ren")//name = "Renhairui"

Record: Swift Learning note 0-1

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.