swift基礎(chǔ)知識1

最近在學(xué)習(xí)swift,把我學(xué)習(xí)內(nèi)容分享給跟我一樣在學(xué)習(xí)swift的小伙伴。


import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

self.title = "基本用法"

self.base();

}

func base() {

//1.變量和常量

let i:Double = 10.5? ? ? ? ? //:后面跟這個變量的類型

let j:Double = 20.6

var k:Int = Int(i) + Int(j)? //let 不可更改的變量? var 可以被修改的變量

print(k);

//2. 條件語句

if k == 30 {? ? ? ? ? ? ? ? ? //if之后不需要跟(),直接跟判斷的條件

k = 50

print(k)

}

//3.四種for寫循環(huán)的方式

for var i = 0; i < 10; i++ {

print("1",i)

}

for i in 0..<10 {

print("2",i)

}

for i in 0...10 {

print("3",i)

}

for _ in 0...10 {

print("hello")

}

//4.字符串

let word:String = "qqheillow"

//遍歷字符串

for i in word.characters {

print(i)

}

//字符串拼接

var word1 = word + "hellow"

print(word1)

word1 = word1 + "hei myfriend"

print(word1)

var str:NSString = "qqqwww"

var str1:NSString = "eeerrr"

//拼接

str = str.stringByAppendingFormat(str1, 0)

print(str)

str = str.stringByAppendingString(str1 as String)

print(str)

str1 = (str as String) + (str as String)

print(str1)

//替代

str = str.stringByReplacingCharactersInRange(NSMakeRange(0, 4), withString: "eee")

print(str)

//? ? ? 5.數(shù)組,不可變數(shù)組不能增加元素

let array:NSArray = ["123","234"]

for arr in array {

print(arr)

}

let arr = NSArray(array: ["1","2","3"])

print(arr)

//數(shù)組,可變數(shù)組

let marray:NSMutableArray = ["1","2"]

//添加元素

marray.addObject("123")

print(marray)

marray.addObject("11233")

//移除最后一個元素

marray.removeLastObject()

//在指定位置插入指定元素

marray.insertObject("333", atIndex: 2)

print(marray)

//刪除制定位置的元素

marray.removeObjectAtIndex(0)

print(marray)

//代替制定位置的元素

marray.replaceObjectAtIndex(1, withObject: "1111")

print(marray)

//數(shù)組之間拼接

marray.addObjectsFromArray(["11123","3333333"])

print(marray)

//6.字典

//不可變字典

let dic:NSDictionary = ["name":"wlx","age":"23","tall":"165cm"]

print(dic)

let dict:NSDictionary = NSDictionary(dictionary: ["name":"wlx","age":"23","tall":"165cm"])

print(dict)

let ddict = NSDictionary(dictionary: dict)

print(ddict)

//可變字典

let mdict = NSMutableDictionary(dictionary: ["2":"a"])

mdict.setObject("b", forKey: "1")

print(mdict)

let mmdic = NSMutableDictionary()

//增加元素

mmdic.setObject("11123", forKey: "abc")

mmdic.setObject("11124", forKey: "qwe")

mmdic.setObject("11125", forKey: "rty")

mmdic.setObject("11126", forKey: "dfg")

print(mmdic)

//刪除元素

mmdic.removeObjectForKey("abc")

print(mmdic)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}


后續(xù)會持續(xù)更新我的學(xué)習(xí)內(nèi)容。一直到各種控件的基本使用,閉包,代理的使用等等。如果有什么錯誤,歡迎指出,期待共同進(jìn)步。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容