swift和oc不一樣的地方swift
//類 屬性 對象 Foundation (NSArray NSDictionary NSString)數組
//if bool enum switch forapp
1.如何定義變量和常量ide
let age = 20url
var num = 24spa
swift中變量有自動類型推斷對象
num = 30是對的字符串
num = 1.5是錯誤的 由於上面num=24系統已經默認num是整型了get
能夠在聲明的時候肯定變量的類型string
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{
}