[Swift learning] Swift programming journey (1): swift learning programming journey

Source: Internet
Author: User

[Swift learning] Swift programming journey (1): swift learning programming journey

The most classic example of learning a new language is to output "Hello World !"

Print ("Hello World! ") Swift is output in this way.

If you have used other languages, you may be familiar with them. But it is much simpler than some c.

1. You do not need to import some separate libraries, such as input/output or string processing class libraries,

2. You do not need to write code globally as an entry point program, so you do not need the main () function,

3. You do not need to write a semicolon at the end of each statement. Is this easy to write ~


  Simple Value

Use let to declare a constant and var to declare a variable. A constant value does not need to be known during compilation, but you can only assign values once. We need to assign values during declaration. If multiple values are assigned, a compilation error occurs, as shown in figure

A variable value can be assigned a value upon declaration or later.

Constants or variables must be of the same type as the values assigned to them. However, the declared type is optional. If the declared value is assigned at the same time, the compiler will automatically infer the type. In the preceding example, the compiler deduced that var1 is an integer because its initial value is an integer.

If the initial value does not provide enough information (or there is no initial value), declare the type after the variable and separate it with a colon. Values are not implicitly converted to other types and must be converted explicitly. For example, if the conversion is not explicit, a compilation error occurs. For example, the simplest conversion is to write the value into parentheses, write a naming rule for constants and variables before brackets. You can use any character you like as the constant and variable name, including Unicode characters: Even if you use a Chinese constant name, there is no problem 2. Constants and variable names cannot contain k mathematical symbols, arrows, reserved (or invalid) Unicode code bits, connections and tabs3. Cannot start with a number4. Once you declare a constant or variable as a definite type, You cannot use the same name to declare it again.Or change the type of the stored value. At the same time, you cannot convert constants and variables. 5. Avoid using keywords as constant or variable names Array and DictionaryUse [] to create arrays and dictionaries, and access elements through array indexes or dictionary keys. Elements are separated by commas.
var shoppingList = ["catfish", "water", "tulips", "blue paint"]shoppingList[1] = "bottle of water" var occupations = [    "Malcolm": "Captain",    "Kaylee": "Mechanic",]occupations["Jayne"] = "Public Relations”

Let's take a look at the results.


OK! As we expected.


Next we will create an empty array and dictionary.

Let emptyArray = [String] () // create a character-type array let emptyDict = [String: float] () // create a key as the character type, A dictionary with a value of the floating point type


If the type can be inferred, you can use [] and [:] to create an empty array and dictionary.


Control Flow

Use if and switch to perform conditional operations, and use for-in, for, while, repeat-while to perform cyclic operations. The parentheses of the condition or loop variable are optional, but the braces ({}) of the statement body are required.

Let individualScores = [75, 43,103, 87, 12] var teamScore = 0for score in individualScores {if score> 50 {teamScore + = 3} else {teamScore + = 1} print (teamScore) // output 11


In an if statement, the condition must be a Boolean expression. Here we can clearly see the concise swift syntax.

var optionalString: String? = "Hello"print(optionalString == nil) var optionalName: String? = "John Appleseed"var greeting = "Hello!"if let name = optionalName {    greeting = "Hello, \(name)"}


Output result:


Hello, John Appleseed

BecauseOptionalString andOptionalName allIs specific, but ifIf optionalName = nilThe greeting output is Hello!


Var optionalName: String? = "John Appleseed" var greeting = "Hello! "If let name = optionalName {greeting =" Hello, \ (name) "} else {greeting =" Hello, anonymous "}


Output result




The switch supports any type of data and various comparison operations. It is not limited to Integers and equal tests.

let vegetable = "red pepper"switch vegetable {case "celery":    print("Add some raisins and make ants on a log.")case "cucumber", "watercress":    print("That would make a good tea sandwich.")case let x where x.hasSuffix("pepper"):    print("Is it a spicy \(x)?")default:    print("Everything tastes good in soup.")}



The output result is

Is it a spicy red pepper?











Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.