区别
- 首先使用Xcode新建项目,快捷键cmd+shift+n,不同点:
- Language选择swift
- 打印时不再有
%s
的概念统一使用\()
- 声明变量 统一使用var 或let 并且一定要有初始值
+ 例:var flipCount = 0
- 在定义的变量的后面可以跟
didSet{//监听flipCount属性变化,并执行方法}
- 例:
var flipCount = 0 { didSet { flipCountLabel.text = "Flips: \(flipCount)" } }
swift称:Property observer - 这里注意懒加载的时候不能使用didSet{}
- 例:
- struct和class区别
- struct没有继承比class简单
- struct是值类型,class是引用类型
- 值类型:当你将它作为参数传递时,将它放在一个数组中,甚至分配给一个变量,它会被复制。属于在栈层次,拷贝属于深拷贝,即多个变量的操作互不影响。
- 引用类型:在堆层次,拷贝带有指针,拷贝的时候是传递的指针,多个变量可能同时指向同一个指针。
- for 循环写法:
- 例如:
for (i = 0.5; i <= 15.25; i += 0.3 )?
在swift中是不能的,但是有另外一种
stride写法:
- 例如:
stride(from: 0.5, through: 15.25, by: 0.3) {}
- 枚举enum,更加强大:
enum FastFoodMenuItem {
case hamburger(numberOfPatties: Int)
case fries(size: FryOrderSize)
case drink(String, ounces: Int)
case cookie
}
enum FryOrderSize {
case large
case small
}
同时接受时使用switch,同样switch也更强大
let menuItem = FastFoodMenuItem.hamburger(patties:2)
var otherItem: FastFoodMenuItem = .cookie
var yetAnotherItem = .cookie //Swift can‘t figure this out
//~~这里注意:Swift是强类型的语言,你不指定类型,它就不知道你的类型是什么。所以必须指定类型~~
实用
Extension的使用:
例:
func emoji(for card: Card) -> String {
let randomIndex = Int(arc4random_uniform(UInt32(emojiChoices.count)))
emoji[card.identifier] = emojiChoices.remove(at: Int(randomIndex))
}
return emoji[card.identifier] ?? "?"
}
代码可读性差,可以用Extensiton
extension Int {
var arc4random: Int {
if self > 0 {
return Int(arc4random_uniform(UInt32(self)))
} else if self < 0 {
return -Int(arc4random_uniform(UInt32(abs(self))))
} else {
return 0
}
}
之后:
func emoji(for card: Card) -> String {
if emoji[card.identifier] == nil, emojiChoices.count > 0 {
emoji[card.identifier] = emojiChoices.remove(at: emojiChoices.count.arc4random)
}
return emoji[card.identifier] ?? "?"
}
枚举也是值类型(struct)