Swift
swift和oc不同的地方
//类 属性 对象 Foundation (NSArray NSDictionary NSString)
//if bool enum switch for
1.如何定义变量和常量
let age = 20
var num = 24
swift中变量有自动类型推断
num = 30是对的
num = 1.5是错误的 因为上面num=24系统已经默认num是整型了
可以在声明的时候确定变量的类型
var count:Int = 23
2.字符串 String
定义字符串
let name:String = "wangkaiyu"
var address:String = String()
打印字符串
print(name)
print("My name is \(name)")
截取某段字符串或者获取字符串的唱的
(name as NSString).substringToIndex(4)
(name as NSString).substringWithRange(NSMakeRange(4, 5))
(name as NSString).length
3.数组Array
//OC数组里面只能存放对象 swift里面可以存放任意类型
//但是一次只能存放同一种类型 定义成什么类型就存放什么类型
var heightArray:Array<Int> = Array()
heightArray.append(3)
heightArray .insert(4, atIndex: 1)添加元素
4.if语句
for index in 1...5{
print(index)
}
//用于快速枚举
namesArray.appendContentsOf(["Ellis", "Alisa"])
for name in namesArray{
print(name)
}
//用于字典的遍历
let numberOfLegs:[String:Int] = ["cat":4, "duck":2]
for (name, legs) in numberOfLegs{
print("name:\(name) leg:\(legs)")
}
5.swift支持多种命名格式
let 我的名字:String = "wky"
print(我的名字)
let 学生的身高:Array<Int> = [10,20,30]
print(学生的身高[0])
6.元祖
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("(0, 0) is at the origin")
case (_, 0):
print("(\(somePoint.0), 0) is on the x-axis")
case (0, _):
print("(0, \(somePoint.1)) is on the y-axis")
case (-2...2, -2...2):
print("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
print("(\(somePoint.0), \(somePoint.1)) is outside of the box")
}
let studentInfo = (pName:"wky", pAge:23, pHeight:170)
studentInfo.pName
7.枚举
enum CompassPoint {
case North
case South
case West
case East
}
let direction:CompassPoint = .North
8.结构体(值传递 会自动添加对应的init方法)
struct MusicModel {
var name:String?
var url:String?
var singer:String?
}
let model:MusicModel = MusicModel(name: "哈哈哈", url: "http://www.baidu.com", singer: "哈哈哈")
var model2 = model;
model2.name = "呵呵呵"
model.name
结果还是model的哈哈哈 并没有变成呵呵呵
所以使用结构体时 把一个变量赋给另一个变量 改变另一个变量的值 原来的变量的值是不会发生改变的
9.类
类里面声明变量一定要给初值(如果没有初值 就在变量后面加上?表示可选值)
init方法必须自己实现
class Student: NSObject {
var name:String?
var _url:String?
var url:String{
set{
self._url = newValue
}
get{
return self._url!
}
}
init(name:String, url:String) {
super.init()
self.name = name
self.url = url
}
//没有返回值 -> Void省略
func test(a:Int, b:String){
}
func test2(a:Int, b:String) -> String{
return ""
}
}
let xw = Student(name: "快乐崇拜", url: "http://www.baidu.com")
var zs = xw;
zs.name = "七里香"
xw.name
结果就变成七里香了
所以类 和 结构体不同的就是把一个变量赋值给另一个变量 当另一个变量当中的值改变的时候原来的变量里面的值也会随之改变
10.extension 可以用来添加新的方法
extension Student{
func test3(){
}
}
这就给上面的Student类别添加了第三个方法
extension MusicModel{
}