swift入门基础
程序员文章站
2024-02-20 18:57:16
...
import Foundation
var a = 1 //变量
var b = 2
let c = a + b //常量
var str = "Hello "
var s:String = "world" //指明一个数据类型
var i:Int = 10
var strs = str + "hi sam" //字符串连接
strs = str + "\(a)"
var arr = ["hello","world",1.2322,100] //数组
//println(arr[3])
//println(arr)
var arr1 = [] //创建一个空数组
var arr2 = String[]() //创建一个Stringl类型的数组
var dict = ["name":"sam","hello":"world"] //字典
dict["age"] = "\(99)"
dict["sex"] = "female"
//println(dict["name"])
//println(dict)
//-------------------------------------for循环---------------------------------------------------------
for i in 0..100{ //循环
// println("\(i)")
}
var arrItem = String[]()
for i in 0..100{
arrItem.append("sam \(i)");
}
//println(arrItem)
for value in arrItem{ //遍历数组
// println(value)
}
//--------------------------------------while循环-------------------------------------------------------
var j = 0
while j < 10{
// println(j)
j++
}
for (key,value) in dict{ //遍历字典
// println("\(key),\(value)")
}
//--------------------------------------条件判断-------------------------------------------------------
for i in 0..100{
if i%2 == 0{
// println("\(i)")
}
}
var myName:String? = " sam"
//myName = nil
if let name = myName{
// println("welcome \(name)")
}
//--------------------------------------函数-------------------------------------------------------
func sayHi(name:String){
// println("hi \(name)")
}
//sayHi("sam")
func sayHi2(name:String)->String{
return "hi \(name)"
}
//println(sayHi2("sam2"))
var funSay = sayHi2
//println(funSay("funSam"))
//返回多个参数
func getGasPrices() -> (Double, Double, Double) {
return (2.3,2.4,22.11)
}
let (d,e,f) = getGasPrices()
//println(d)
//println(getGasPrices())
//--------------------------------------类-------------------------------------------------------
class Hi{
func sayHi(name:String){
println("Hi \(name)")
}
}
var hi = Hi()
//hi.sayHi("sam")
class Hello:Hi{
var _name:String
init(name:String){
self._name = name
println("构造方法")
}
func sayHi(){
println("hello \(self._name)")
}
//重写父类函数
override func sayHi(name:String){
println("override hello \(name)")
}
}
var hello = Hello(name: "sam")
hello.sayHi()
hello.sayHi("sam")
转载于:https://my.oschina.net/u/1264926/blog/272359
上一篇: php史上公认最安全的正反加密解密函数