let val = (Double)6
参考:The Swift Programming Language: Language Guide: The Basics: Constants and Variables
let x = 5
guard x == 5 { return }
guard
缺少了 else
guard
缺少了 then
参考:The Swift Programming Language: Language Guide: Control Flow: Early Exit
enum Direction {
case north, south, east, west
}
String
Any
Int
参考:The Swift Programming Language: Language Guide: Enumerations: Raw Values
let val = 5
print("value is: \(val)")
参考:The Swift Programming Language: Language Guide: Strings and Characters: String Interpolation
vals
的内容是什么?var vals = [10, 2]
vals.sort { (s1, s2) -> Bool in
s1 > s2
}
[10, 2]
[2, 10]
nil
typealias Thing = [String: Any]
var stuff: Thing
print(type(of: stuff))
Dictionary<String, Any>
Dictionary
Error
Thing
参考:The Swift Programming Language: Language Reference: Types: Type Identifier
let x = ["1", "2"].dropFirst()
let y = x[0]
1
2
nil
解释
Swift.Collection.Array
中的 dropFirst()
返回一个 ArraySlice<Element>
类型
如文档所述:
@inlinable public func dropFirst(_ k: Int = 1) -> ArraySlice<Element>
ArraySlice 类型使您能够快速有效地在较大数组的各个部分执行操作。与将一个切片的元素复制到新存储中不同,ArraySlice 实例提供了对较大数组的存储的视图。由于 ArraySlice 提供与 Array 相同的接口,因此您通常可以对切片执行与原始数组相同的操作。
切片保留索引
与 Array 和 ContiguousArray 不同,ArraySlice 实例的起始索引并不总是零。切片保持较大数组的相同元素的相同索引,因此切片的起始索引取决于如何创建它,从而使您能够在完整数组或切片上执行基于索引的操作。
以上代码返回值的切片为 ["2"]
,但索引未更改。let y = x[1]
将给出预期结果。
为了安全地引用切片的起始和结束索引,请始终使用 startIndex 和 endIndex 属性,而不是具体值。
参考
var test = 1 == 1
true
YES
1
参考:The Swift Programming Language: Language Guide: Basic Operators: Comparison Operators
var x: Int?
let y = x ?? 5
5
0
nil
参考:The Swift Programming Language: Language Guide: Basic Operators: Nil-Coalescing Operators
func add(a: Int, b: Int) -> Int { return a+b }
Int
(Int, Int) -> Int
Int<Optional>
参考:The Swift Programming Language: Language Guide: Functions: Function Types
func
myFunc(_ a: Int, b: Int) -> Int {
return a + b
}
myFunc(5, b: 6)
myFunc(5, 6)
myFunc(a: 5, b: 6)
myFunc(a, b)
Encodable
和 Decodable
的结合 参考:
let value1 = "\("test".count)"
String
Int
null
test.count
参考:The Swift Programming Language: Language Guide: Strings and Characters: String Interpolation
参考:The Swift Programming Language: Language Guide: Closures: Escaping Closures
class Person {
var name: String
var address: String
}
var name
格式不正确。 address
是一个关键字。 参考:The Swift Programming Language: Language Guide: Initialization: Class Inheritance and Initialization
let names = ["Bear", "Joe", "Clark"]
names.map { (s) -> String in
return s.uppercased()
}
["BEAR", "JOE", "CLARK"]
["B", "J", "C"]
["Bear", "Joe", "Clark"]
let val = 5
Int
的常量名为 val item
的变量名为 val Number
的常量名为 val Int
的变量名为 val 参考:The Swift Programming Language: Language Guide: The Basics: Type Safety and Type Inference
extension String {
var firstLetter: Character = "c" {
didSet {
print("new value")
}
}
}
didSet
接受一个参数。 c
不是一个字符。 参考:The Swift Programming Language: Language Guide: Extensions: Computed Properties
newOld
值调用 参考:The Swift Programming Language: Language Guide: Properties