Swift Overview Essentials

Source: Internet
Author: User

Yesterday, the book summed up the Swift key part of the study finished, some very easy to understand, but also do not understand, do not understand the first mark, in the book behind each knowledge point of the detailed tutorial inside to understand the line.

The layout of the book is very learning-oriented, first of all, the knowledge points involved in a small part of the book to let readers have a certain understanding of the whole books, the later study plan will be clearer, not the beginning is a variety of boring concepts introduced what, will hit the reader's interest. Look at the following study summary, it looks very easy to learn the passion explosion!

The following code basically no explanation, just started to learn, there is no own opinion can write @[email protected]!

Import Foundation

Hello, world!. is to create a command-line program Yes, run it, go into the pit.

println ("Hello, world!")

constants, variable declarations, VAR represents constants, let represents variables, data types are written after variable names Ex:int
var myvariable = 42
myvariable = 50
Let myconstant = 42

Let label = "the width is"
Let width = 94
Let Widthlabel = label + "\ (width)"

println (Widthlabel)

var emptyarray = [String] ()
var emptydictionary = dictionary<string, float> ()

emptyarray[1]= "Fuck1"
emptydictionary=["Fuck": 2.0,]

println (width)
println (emptydictionary["fuck"])

All optional types can be assigned nil; let val = nil return false or True?

var optionalstring:string? = "Fuck?"
Optionalstring = Nil

println (optionalstring)

var optionalname:string? = "John Appleseed"
var greeting = "Hello!"
Optionalname = Nil
println (Optionalname)
If let name = optionalname {
Greeting = "Hello, \ (name)"
}
else {
greeting = "Fuck u"
}

println (greeting)

A simple loop

var firstforloop = 0
var j=[2,4,6]
For I in J {
Firstforloop + = i
println (i)
}
println (Firstforloop)
println (1...3)

A simple function

Func greet (name:string, day:string), String {
Return "Hello \ (name), today is \ (day)."
}
println (Greet ("Bob", "Tuesday"))

Func Returnfifteen (), Int {
var y = 10
Func Add () {
Y + = 5
}
Add ()
Return y
}
println (Returnfifteen ())

function nesting, can multiple nesting, recursive? Look back. The return value is the return value of the nested function (int, int)


Func Makeincrementer ()-(int-int) {
Func AddOne (number:int), Int {
Return 1 + number
}
Return AddOne
}
var increment = Makeincrementer ()

println (Increment (7))

The condition parameter calls the return value of the other function, Int--Bool

Func hasanymatches (list: [int], condition:int-Bool), Int {
For item in list {
If condition (item) {
Return item
}
}
Return 10
}
Func Lessthanten (number:int), Bool {
Return number < 10
}
var numbers = [20, 19, 7, 12]
println (Hasanymatches (Numbers, Lessthanten))

Find Average @ @!
Func sumof (Numbers:int ...), Int {
var sum = 0
var i = 0
For number in numbers {
Sum + = number
i++
}
If i==0 {
return I
}
else {
Return sum/i
}
}
println (Sumof ())
println (Sumof (42, 597, 12))


Something unsolved below
Numbers.map ({
(Number:int), Int in
Let result = 3 * number
return result
})

println (Numbers.map (1))

Sort ([1, 5, 3, 2]) {$ > $}

@end

The definition constructor for a simple class init can write like this, and go back to studying

Class Shape {
var numberofsides = 0
var name:string? = Nil
var val:int? = Nil

Init () {

}

Init (name:string,val:int) {
Self.name = Name
Self.val = Val
}

Func simpledescription (), String {
If val! = Nil && Name! = Nil {
Return "\ (val!) Shape "+name!+" with \ (numberofsides) sides. "
}
Else
{
Return "A shape with \ (numberofsides) sides."
}
}
}

Class Shapelen:shape {
var len:int? = Nil
Override Init () {
//}
Init (name:string,val:int,len:int) {
Self.len=len
Super.init (Name:name, Val:val)
}

var Gslen:int {
get {
Return len! * Numberofsides
}
set {
Len = newvalue
}
}

Override Func Simpledescription (), String {
Return "\ (val!) Shape "+name!+" with \ (Numberofsides) \ (len!) sides. "
}
}

var Lenshape=shapelen (name: "Square", Val:2,len:2)
lenshape.numberofsides=2
Lenshape.gslen=3
println (Lenshape.gslen)

var shapeins=shape (name: "Square", Val:2)
shapeins.numberofsides=666
println (Shape (). Simpledescription ())
println (Shapeins.simpledescription ())

The simple enumeration definition, which adds an all enumeration, returns all the enumeration values, can swift give me a all?


Enum Rank:int {
Case ACE = 1
Case A, three, four, Five, Six, Seven, Eight, Nine, Ten
Case Jack, Queen, King, all
Func simpledescription (), String {
Switch Self {
Case. Ace:
Return "Ace"
Case. Jack:
Return "Jack"
Case. Queen:
Return "Queen"
Case. King:
Return "King"
Case. All:
Return "Ace,1,2,3,4,5,6,7,8,9,10,jack,queen,king"
Default
Return String (Self.rawvalue)
}
}
}
Let Ace = Rank.jack
Let Acerawvalue = Ace.rawvalue

println (Ace.simpledescription ())
println (Acerawvalue)

Enum Suit {
Case Spades, Hearts, Diamonds, Clubs, all
Func simpledescription (), String {
Switch Self {
Case. Spades:
Return "Spades"
Case. Hearts:
Return "Hearts"
Case. Diamonds:
Return "Diamonds"
Case. Clubs:
Return "clubs"
Case. All:
Return "Spades,hearts,diamonds,clubs"
}
}

}
Let hearts = Suit.hearts
Let heartsdescription = Hearts.simpledescription ()

Simple structure definition

struct Card {
var Rank:rank
var suit:suit
Func simpledescription (), String {
Return "The \ (Rank.simpledescription ()) of \ (Suit.simpledescription ())"
}

Output whole deck of poker, not yet finished writing T T
/*
Func Createall () {
For-ran in Rank.All.simpleDescription (). componentsseparatedbystring (",") {
println ("")
}
*/
}

Let Threeofspades = Card (rank:. Three, suit:. Spades)
Let threeofspadesdescription = Threeofspades.simpledescription ()

The switch method of the enum was written outside, and for the time being, there was no sense in the writing. The first pit of a little pit crawl


Enum Serverresponse {
Case Waiting (String)
Case Result (String, String)
Case Error (String)
}

Let success = Serverresponse.result ("6:00pm", "8:09 PM")
Let failure = Serverresponse.error ("Out of cheese.")
Let wait = serverresponse.waiting ("Server is Responing")


Func serverstate (state:serverresponse), String {
var serverresponse:string
Switch State {
Case Let. Result (Sunrise, Sunset):
Serverresponse = "Sunrise are at \ (Sunrise) and sunset are at \ (sunset)."
Case Let. Error (Error):
Serverresponse = "Failure ... \ (Error)"
Case Let. Waiting (Wait):
Serverresponse = "Please wait...\ (wait)"
Default
Serverresponse = "no State"
}
Return Serverresponse
}


println (ServerState (Wait))

Simple interface protocol Definition it's so cool, it's blinding. Add a method to the int inside pressure yajing

Use extension to add functionality to an existing type, such as adding a method that calculates a property. You can use extensions to add protocols to any type, even types that you import from external libraries or frameworks.

Protocol Exampleprotocol {
var simpledescription:string {Get}
Mutating func adjust ()
}

Class Simpleclass:exampleprotocol {
var simpledescription:string = "A very simple class."
var anotherproperty:int = 69105
Func Adjust () {
Simpledescription + = "Now 100% adjusted."
}
}

/*something Unsolved below
Enum Exampleprotocolenum:exampleprotocol {
Case Other1,other2
var simpledescription:string {
get {
Switch Self {
Case. Other1:
Return "A very simple enum1."
Case. Other2:
Return "A very simple enum2."
Default:
Return "no enum"
}
}
set {
Switch Self {
Case Let. Other1:
Self.simpledescription= "A very simple enum1."
Case Let. Other2:
Self.simpledescription= "A very simple enum2."
Default:
self.simpledescription= "No enum"
}
}
}

Mutating func adjust (), string{
//
}

}
*/


Extension Int:exampleprotocol {
var simpledescription:string {
Return "the number \ (self)"
}
Mutating func adjust () {
Self + = 42
}
}

var testextension:int = 10
Testextension.adjust ()
println (testextension.simpledescription)

Generic feel direct amplification I didn't understand the back and went on.
Func repeat<itemtype> (Item:itemtype, times:int), ItemType {
var result:itemtype? = Nil
println (Item,times)
For I in 0...times {
result = Item
}
Return result!
}
println (Repeat ("knock", 4))


Enum Optionalvalue<t> {
Case None
Case Some (T)
}
var possibleinteger:optionalvalue<int> =. None
Possibleinteger =. Some (100)

/*something Unsolved below

Func anycommonelements <t, U where t:sequence, U:sequence, t.generatortype.element:equatable, T.GeneratorType.Eleme NT = = u.generatortype.element> (Lhs:t, rhs:u), Bool {
For Lhsitem in LHS {
For Rhsitem in RHS {
if Lhsitem = = Rhsitem {
return True
}
}
}
return False
}
Anycommonelements ([1, 2, 3], [3])

*/

That ' s all! Thanks

Swift Overview Essentials

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.