Swift Fundamentals: Creating the First Swift Project: basic syntax for Swift

Source: Internet
Author: User
Tags case statement unpack



In addition to the release of IOS8 and Max OS X 10.10, Apple released a new programming language, Swift, at this year's WWDC conference. It has to be said that Swift has a big change and makes programming easier, and the following describes the definition of constants and variables for Swift, the use of basic control statements:



It is important to note that Swift can only be run in the Xcode 6 beta version, and Xcode 6 is currently the latest Beta 7, which can be downloaded via the following link:



Http://adcdownload.apple.com//Developer_Tools/xcode_6_beta_7_apzr94/xcode_6_beta_7.dmg






Open when the download is complete.






First, create a swift project:






1. Create a swift project:



As shown in, after you open Xcode 6, a welcome screen appears, and the second item is: Create a new Xcode project (creating a newer Xcode project)





650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/48/99/wKioL1QJyfSjfFQgAAGwfG3b8Xo988.jpg "style=" float: none; "title=" Qq20140905-1.png "alt=" Wkiol1qjyfsjffqgaagwfg3b8xo988.jpg "/>






2. On the Choose a template for your new project: page, select Application under OS X and select command line Tool on the right, then click Next (as shown):



650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/48/97/wKiom1QJye6CNTMdAAFxDjqh_7w419.jpg "style=" float: none; "title=" Qq20140905-2.png "alt=" Wkiom1qjye6cntmdaafxdjqh_7w419.jpg "/>



3. In choose options for your new project: interface, first enter the project name, then remember to select Swift in language, then proceed to next ():



650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/48/97/wKiom1QJye6xOQCfAAFQQXTIFc8421.jpg "style=" float: none; "title=" Qq20140905-3.png "alt=" Wkiom1qjye6xoqcfaafqqxtifc8421.jpg "/>



4. Select the path, this does not need to say more, and then create ():



650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/48/99/wKioL1QJyfSQWYXkAAImP2KZy8U898.jpg "style=" float: none; "title=" Qq20140905-4.png "alt=" Wkiol1qjyfsqwyxkaaimp2kzy8u898.jpg "/>



5. Then you will see the following interface, click on the left side of the project's lower triangle, there is a Main.swift file, click After:



650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/48/97/wKiom1QJye6A1HBLAAQZe7uhk98035.jpg "style=" float: none; "title=" Qq20140905-5.png "alt=" Wkiom1qjye6a1hblaaqze7uhk98035.jpg "/>



6. Click the Run button (shortcut: Command + R) in the upper left corner, and you will find the console print out the first sentence of all programming languages: Hello,world, the Swift project has been created.









Second, the basic syntax of Swift:






The following is a brief introduction to Swift's basic usage (code in Main.swift ) :








import Foundation

println ("Hello, World!")
println ("Hello world!")

// define a constant, use the keyword "let"
// In Swift, almost all basic data types or object types are rewritten using structures
let haiDian = "Haidian"
// let haiDian: String = "海 addy" // In Swift, the system will do the type inference for you, the code on the previous line is the same as this line
// \ (variable name) converts a variable or constant name into a string for output
println ("haiDian = \ (haiDian)") // "\ (variable / constant name)" can convert variables / constants into strings
// Direct output
println (haiDian)


// define a variable, use the keyword "var"
var hello = "Hello,"
hello = hello + haiDian // string overload: string concatenation
println ("hello = \ (hello)")


// Swift supports almost all Unicode-encoded characters (except symbols, arrows, and horizontal lines in math) to name variables / constants
let dog = "Dog,"
println (dog)

var = dog + "love you"
println ()

// define an integer (type inference)
var a = 10 // Define an integer. In fact, the compiler will infer this statement as: var a: Int = 10, the format is "variable / constant name: type". In Swift, the integer is Int. If the system is 32-bit, then this variable is Int32. If the system is 64-bit, then Int64. If I define an 8-bit integer tree, I need to explicitly specify Int8:
var b: Int8 = 12 // explicitly specify the number of digits of Int

var c = 12.0 // In Swift, floating-point data is Double by default
var d = Double (b) + c // In Swift, implicit conversion is not supported. If you want to operate on two different types of data, you need to explicitly convert its type. The conversion format is: "type name ( Constant / variable name) "



// Tuples. The tuples borrow the concepts from a relational database. A piece of data in a relational database is a tuple. Tuples can store different types of data, similar to structures, but structures need to be declared , Tuples can be created directly using
// define a tuple
let errorCode = (404, "Not Fount") // This is a tuple of type (Int, String), which is equivalent to: let errorCode: (Int, String) = (404, "Not Fount")
// element decomposition (remove the elements in the tuple)
// take out the elements in the tuple (take out through the subscript)
println ("errorCode = \ (errorCode.0), errorMessage = \ (errorCode.1)")


// When creating a tuple, you can declare the type name for the elements in the tuple
let errorCodeA = (errorCode: 404, errorMessage: "Not Found")
// remove element by type name
println ("errorCode = \ (errorCodeA.errorCode), errorMessage = \ (errorCodeA.errorMessage)")
println (errorCodeA)

// If you ignore the element at the corresponding position of the tuple, you can use "_"
let (statusCode, _) = errorCodeA
println ("statusCode = \ (statusCode)")


// Array: In a Swift array, you can only store data of the same type, so that you can access the array. If the data types are not the same, it will be converted to NSArray for processing

// use var to declare a mutable array,
var nameArrayA = ["Zhang San", "Li Si", "Wang Wu"] // Equivalent: var nameArrayA: String [] = ["Zhang San", "Li Si", "King Wu", "Zhao Liu "]
println ("nameArrayA = \ (nameArrayA)")


// define an empty array
var someValues = [Int] () // declares an empty array, the elements in the array are all Int, before Xcode6 Beta4, the version is: Int [] ()
var nameArrayC = ["Hello", 123]

// add elements to the array
nameArrayA.append ("Zhao Liu")
println ("nameArrayA = \ (nameArrayA)")


// replace elements in the array
nameArrayA [0] = "First"
println (nameArrayA)

// delete elements in the array
nameArrayA.removeAtIndex (0)
println (nameArrayA)

// delete the last element
nameArrayA.removeLast ()
println (nameArrayA)


// Define immutable arrays. The mutable and immutable arrays are declared through let and var. Before Xcode6 beta4, immutable arrays (constant arrays) cannot add and delete elements, but you can change elements, but After Xcode6 Beta4, the elements of the constant array cannot be changed
let nameArrayD = ["张三", "李四", "王 五"]
// nameArrayD [0] = "Replace"
for name in nameArrayD {
    println ("name = \ (name)")
}

// both take out the elements in the array and get the index of the element, you need to use the enumerate (array name) method
for (index, name) in enumerate (nameArrayD) {
    println ("index = \ (index), name = \ (name)")
}


// Dictionary. In Swift, all the keys of the dictionary are of the same type, and all the Values are of the same type. Key and value can be different types. If they are not the same type, they are automatically converted to NSDictionary in OC
// declare an empty dictionary
var dictionaryStudent = Dictionary <String, Float> ()

var person = ["name": "Brother Brother", "sex": "Male"] // Equivalent: var person: Dictionary <Sting, String> = ["name": "Brother Brother", "sex": "male"]
println ("person = \ (person)") // the printing of the dictionary is out of order

// add keys to dictionary
person ["habit"] = "Smoking"
println ("person = \ (person)")
// If the key does not exist in the dictionary, then add it directly, if the key already exists, then replace the previous value directly
person ["name"] = "Bogo"
println ("person = \ (person)")
// Update the value corresponding to a key. When using updateValue (value, forKey: key) to update, the old value before the update will be returned
let oldValue = person.updateValue ("Trige", forKey: "name")
println ("person = \ (person), oldValue = \ (oldValue)")
// traversal of the dictionary
for (key, value) in person {
    println ("key = \ (key), value = \ (value)")
}

// The dictionary's mutable and immutable are also controlled by let and var, and the constant dictionary cannot be updated



// Control statements: if, if ... else, while, do ... while, switch ... case
var num = 3
var condition = true
// if num {// Without parentheses, the following judgment conditions can only be Bool type, integers and other types are not allowed
// println ("This is an integer")
//}
if condition {
    println ("This is a Bool value")
}

for var i = 0; i <10; i ++ {
    println ("i = \ (i)")
}

for j in 0 .. <3 {// ".. <" includes the left, not the right. For versions before Xcode6 Beta4, use ".."
    println ("j = \ (j)")
}

for j in 0 ... 4 {// "..." includes both left and right
    println ("j = \ (j)")
}



// switch, in Swift, a lot of changes have been made to the switch, no need to write break by default
var number = 20
switch number {
case 10:
    println ("number = 10")
case 20:
    println ("number = 20")
default:
    println ("other")
}

// If you want to enforce the next statement, you need to use the fallthrough keyword, this statement must meet the conditions
var numberA = 10
switch numberA {
case 10:
    println ("number = 10")
    fallthrough
case 20:
    println ("number = 20")
// fallthrough // equivalent to not writing break in OC
default:
    println ("other")
    
}

// case is a range
var numberB = 12
switch numberB {
case 1 .. <10:
    println ("This is a single digit")
case 10 .. <100:
    println ("This is two digits")
default:
    println ("This is another number")
}
// case ranges can be crossed, but only the first case statement that meets the conditions is executed
var numberC = 12
switch numberC {
case 1 .. <20:
    println ("between 1 and 20")
case 10 .. <100:
    println ("between 10 and 100")
default:
    println ("Other")
}

// Double judgment is possible (using the "where judgment condition" keyword)
var numberD = 13
switch numberD {
case 1 .. <20 where numberD <15:
    println ("numberD = 12")
case 10 .. <100:
    println ("two digits")
default:
    println ("other numbers")
}


// determine where the point is in the coordinate system, "_": ignore the value of the corresponding position in the tuple
var point = (3, 5)
switch point {
case (0, 0):
    println ("origin")
case (_, 0):
    println ("X axis")
case (0, _):
    println ("Y axis")
default:
    println ("in the quadrant")
}

var pointA =(0, 4)
switch pointA {
case (0, 0):
     println ("origin")
case (let x, 0):
     println ("X axis, x = \ (x)")
case (0, let y):
     println ("Y axis, y = \ (y)")
default:
     println ("in the quadrant")
}



// optionals, optional variables. If optionals are used to declare variables, the value of this variable may be nil. (Need attention to unpacking / unpacking)
// In Swift only nil means empty, no Nil, NULL, null, NSNull

var value: Int? // "?" means this is an optional variable, the value may be nil

let numberStr = "123456.3"
value = numberStr.toInt ()
if nil! = value {// After Xcode6 Beta6, Int? cannot be used as a judgment condition, before it can (directly value)
     println ("Has a value: value = \ (value)")
}

var valueA = 21
let valueB = valueA + value! // Unpack / Unpack, if there is no value, it cannot be unpacked
println ("valueB = \ (valueB)")








Which I put the explanations of the various statements in the code, you can paste directly into the project to view, more convenient to learn.









The above is the creation of Swift project and some basic sentences of learning, I hope to be helpful to everyone.



This article is from the "A Mao" blog, please be sure to keep this source http://winann.blog.51cto.com/4424329/1549505



Swift Fundamentals: Creating the First Swift Project: basic syntax for Swift


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.