In depth understanding of swift variables and functions

  • 2020-05-15 02:16:31
  • OfStack

The Swift function is a separate block of code used to accomplish a specific task.

Swift USES a unified 1 syntax to represent simple C language-style functions to complex Objective-C language-style methods.

Function declaration: tells the compiler the name, return type, and parameters of the function.

Function definition: the entity that provides the function.


func getNums()->(Int,Int){ //swift A function can return multiple variables 
return (2,3)
}
let (a,b) = getNums() //let Is constant, 1 Once the value is assigned,  var Is a variable 
println(a) // The output  2
var f = getNums // The function is 1 It's an object 1 Two variables are used. Copy to the other 1 A variable 
println(f()) // The output  (2,3)

swift declares that the variable var name = "Hello" //name will be automatically identified as String

Or specify variable type: var name :String = "Hello"

swift USES + for string concatenation, but not + int. If you want to add type int, you can use the following method:


var i  =  200
var str = "Hello"
str = "\(str) , world , \(i)" // use  \( The variable name )  .  str  The value is  Hello,world,200

You can store different data types in an array


var arr = ["hello", 100, 2.3]

You can also specify that only arrays can be stored:


var arr1 = [] // define 1 An array 
var arr2 = String[]() //arr2 An array of   You can only store strings 

Dictionary:


var dic = ["name":"zhou", "age":"16"]
dic["sex"] = "female" // Dynamically assign a value to a dictionary 
println(dic) // The output   [ sex:female, name:zhou, age:16 ] 
println(dic["name"]) // The output zhou
class Math{
class func max(a:Int, b:Int)->Int{
NSLog("run Math.max") // Print the time, and the string inside 
if(a>b){
return a;
}else{
return b;
}
}
}
var maxNum = Math.max(2, b: 5)
println("Hello, \(maxNum)")

Related articles: