SoFunction
Updated on 2025-04-06

Deep understanding of swift variables and functions

Swift functions are used to complete independent code blocks of specific tasks.

Swift uses a unified syntax to represent simple C-style functions to complex Objective-C-style methods.

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

Function definition: Provides the entity of the function.

func getNums()->(Int,Int){ //Swift function can return multiple variablesreturn (2,3)
}
let (a,b) = getNums() //Let is a constant, it cannot be changed after assignment, var is a variableprintln(a) //Output 2var f = getNums //The function is an object and can be used as a variable.  Copy to another variableprintln(f()) //Output (2,3)

swift declare variable var name = "Hello" //name will be automatically recognized as String type

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

Swift uses + for string concatenation, but cannot be + int type. If you want to add an int type, you can use the following method:

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

Different data types can be stored in arrays

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

You can also specify that only arrays can be stored:

var arr1 = [] //Define an arrayvar arr2 = String[]() //arr2Array Only strings can be stored

dictionary:

var dic = ["name":"zhou", "age":"16"]
dic["sex"] = "female" //Assign dynamic values ​​to the dictionaryprintln(dic) //Output [sex:female, name:zhou, age:16]println(dic["name"]) //Output Zhouclass Math{
class func max(a:Int, b:Int)->Int{
NSLog("run ") //Print time, and string insideif(a>b){
return a;
}else{
return b;
}
}
}
var maxNum = (2, b: 5)
println("Hello, \(maxNum)")

The above is the in-depth understanding of swift variables and functions introduced by the editor to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!