最近在学习swift,把我学习内容分享给跟我一样在学习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写循环的方式
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.数组,不可变数组不能增加元素
let array:NSArray = ["123","234"]
for arr in array {
print(arr)
}
let arr = NSArray(array: ["1","2","3"])
print(arr)
//数组,可变数组
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)
//数组之间拼接
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.
}
}
后续会持续更新我的学习内容。一直到各种控件的基本使用,闭包,代理的使用等等。如果有什么错误,欢迎指出,期待共同进步。