標籤:
昨天一天就把書中概括出來的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
swift概述要點