昨天一天就把书中概括出来的swift重点部分学完了,有些挺容易懂的,也有不懂的,不懂的就先标记,在书本后面对每个知识点的细致教程里面再去弄懂就行。
这本书的编排还是非常有学习引导性的,首先就把全书涉及的知识点抛出一小部分让读者对整本书有一定的了解,对后面的学习计划会更清晰,不会一开始就是各种枯燥的概念介绍什么的,会打击读者的兴趣。看下下面的学习总结吧,看起来挺容易的,学习激情爆炸!
下面的代码基本没什么解释,刚开始学习,没什么自己的见解可写 @[email protected]!
import Foundation
/// Hello, World! 是创建命令行程序就有的,运行一下,正式入坑
println("Hello, World!")
///常量、变量声明,var 表示常量,let 表示变量,数据类型写在变量名后 ex:Int
var myVariable = 42
myVariable = 50
let myConstant = 42
let label = "The width is"
let width = 94
let widthLabel = label + " \(width)"
println(widthLabel)
var emptyArray = [String]()
var emptyDictionary = Dictionary<String, Float>()
//emptyArray[1]="fuck1"
emptyDictionary=["fuck":2.0,]
println(width)
//println(emptyDictionary["fuck"])
///所有可选类型都可以赋值nil; let val = nil 返回false 还是true?
var optionalString: String? = "fuck ?"
//optionalString == nil
println(optionalString)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
optionalName = nil
println(optionalName)
if let name = optionalName {
greeting = "Hello, \(name)"
}
else {
greeting = "fuck u"
}
println(greeting)
/// 一个简单的循环
var firstForLoop = 0
var j=[2,4,6]
for i in j {
firstForLoop += i
println(i)
}
println(firstForLoop)
println(1...3)
///简单的函数
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
println(greet("Bob", "Tuesday"))
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
println(returnFifteen())
///函数嵌套,可否多重嵌套,递归? 后面再看看。返回值是嵌套函数的返回值(Int -> Int)
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
println(increment(7))
///condition参数调用另外一个函数的返回值 Int -> Bool
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Int {
for item in list {
if condition(item) {
return item
}
}
return 10
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
println(hasAnyMatches(numbers, lessThanTen))
///求平均数 @ @!
func sumOf(numbers: Int...) -> Int {
var sum = 0
var i = 0
for number in numbers {
sum += number
i++
}
if i==0 {
return i
}
else {
return sum/i
}
}
println(sumOf())
println(sumOf(42, 597, 12))
//something unsolved below
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
//println(numbers.map(1))
//sort([1, 5, 3, 12, 2]) { $0 > $1 }
//@end
///简单类的定义 构造函数init可以这样写吗,后面继续研究
class Shape {
var numberOfSides = 0
var name:String? = nil
var val:Int? = nil
init() {
}
init(name:String,val:Int) {
self.name = name
self.val = val
}
func simpleDescription() -> String {
if val != nil && name != nil {
return "\(val!) shape "+name!+" with \(numberOfSides) sides."
}
else
{
return "A shape with \(numberOfSides) sides."
}
}
}
class ShapeLen:Shape {
var len:Int? = nil
//override init () {
//}
init (name:String,val:Int,len:Int) {
self.len=len
super.init(name: name, val: val)
}
var GSlen:Int {
get {
return len! * numberOfSides
}
set {
len = newValue
}
}
override func simpleDescription() -> String {
return "\(val!) shape "+name!+" with \(numberOfSides) \(len!) sides."
}
}
var lenShape=ShapeLen(name: "square",val: 2,len: 2)
lenShape.numberOfSides=2
lenShape.GSlen=3
println(lenShape.GSlen)
var shapeIns=Shape(name: "square", val: 2)
shapeIns.numberOfSides=666
println(Shape().simpleDescription())
println(shapeIns.simpleDescription())
///简单枚举定义,自己加了一个all的枚举,返回所有枚举值,swift能给我一个all吗?
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King, All
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
case .All:
return "ace,1,2,3,4,5,6,7,8,9,10,jack,queen,king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Jack
let aceRawValue = ace.rawValue
println(ace.simpleDescription())
println(aceRawValue)
enum Suit {
case Spades, Hearts, Diamonds, Clubs, All
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
case .All:
return "spades,hearts,diamonds,clubs"
}
}
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()
///简单结构体定义
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
///输出整副扑克牌,还没写完 T T
/*
func createAll() {
for ran in Rank.All.simpleDescription().componentsSeparatedByString(",") {
println(" ")
}
*/
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
///把enum的switch方法写在外面了 暂时没感觉这个写法有什么好处啊 略坑 爬的第一个坑
enum ServerResponse {
case Waiting(String)
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
let wait = ServerResponse.Waiting("server is responing")
func serverState(state:ServerResponse) -> String {
var serverResponse:String
switch state {
case let .Result(sunrise, sunset):
serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
serverResponse = "Failure... \(error)"
case let .Waiting(wait):
serverResponse = "Please wait...\(wait)"
default:
serverResponse = "no state"
}
return serverResponse
}
println(serverState(wait))
///简单的接口协议定义 很牛逼,简直亮瞎了 赶紧在Int里面加个方法压压惊
///使用extension来为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
// simpleDescription += " Now 100% adjusted."
}
}
/*something unsolved below
enum ExampleProtocolEnum:ExampleProtocol {
case Other1,Other2
var simpleDescription:String {
get {
switch self {
case .Other1 :
return "A very simple enum1."
case .Other2 :
return "A very simple enum2."
default :
return "no enum"
}
}
set {
switch self {
case let .Other1 :
self.simpleDescription="A very simple enum1."
case let .Other2 :
self.simpleDescription="A very simple enum2."
default :
self.simpleDescription="no enum"
}
}
}
mutating func adjust() -> String{
//
}
}
*/
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
var testExtension:Int = 10
testExtension.adjust()
println(testExtension.simpleDescription)
///泛型感觉直接放大招了 完全没理解 后面再继续研究了
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType {
var result:ItemType? = nil
println(item,times)
for i in 0...times {
result = item
}
return result!
}
println(repeat("knock", 4))
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
/*something unsolved below
func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
*/
///that‘s all ! thanks