加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift学习(一:认识必要数据类型)

发布时间:2020-12-14 01:33:52 所属栏目:百科 来源:网络整理
导读:span style="font-family: Arial,Helvetica,sans-serif; background-color: rgb(255,255,255);"如果你看到这篇文章,说明你有学IOS开的的强烈愿望。/span 我很高兴为你讲解我的学习过程。首先,你会问为什么不选择ObjC而是Swift,我想这个问题只有苹果自己知
<span style="font-family: Arial,Helvetica,sans-serif; background-color: rgb(255,255,255);">如果你看到这篇文章,说明你有学IOS开的的强烈愿望。</span>

我很高兴为你讲解我的学习过程。首先,你会问为什么不选择ObjC而是Swift,我想这个问题只有苹果自己知道,我们只有猜。不过从代码结构上来看Swift确实比OC简洁多了,Swift省掉那些OC难以理解的符号,比如NSLog传递消息时是这么写的:NSLog(@"You code in here"); 学过C#的Programmer应该认识这个@,在OC中我不知道怎么理解,所以就不管了。

那么现在我们就开始,yeah!首先,我强烈建议去买台MAC,也就一万左右。当然,如果你和我一样用的是咱们中国人撑起的Windows,你可以和我一样装个虚拟就OK了。我的虚拟机是:VMware Workstation 12.1.0 + OS X EI Capitan 10.11.2,请原谅我是一个强迫症患者,任何软件都要最新的。

关于如何安装XCode 7.2我就不说了,你去AppStore免费下就OK了!

注:我的笔记都以注释的方式在源码中呈现!!!

学习笔记开始

//
//  main.swift
//  hello word
//
//  Created by YiSong on 12/10/15.
//  Copyright ? 2015 YiSong. All rights reserved.
//

import Foundation

print("------------Hello Word!-----------n")

// Variable 'number' used before being initialized.
var number: Int?
var number2: Int = 100
number = 888
print(number)
print(number2)

/**
* End of every statement have a semicolon.
*/
let mConstant = 9;
var mVariable = 1;
mVariable = 6;
print("Print mVarible and mConstant in string,mVarible:(mVariable) mConstant:(mConstant) n");

/**
* End of every statement without semicolon.
*/
let label = "The width is"
let width = 94
let widthLabel = label +  " " + String(width)
print(label)
print(widthLabel + "n")

/**
* Create arrays and dictionaries using barckets([]).
*/
var shoppingList = ["catfish","water","tulips","bulepaint"];
shoppingList[1] = "apple";
print(shoppingList);
// you should notice,print() method can output a array.

var occupations = [
    "Malcolm" : "Captain","Kaylee" : "Mechainc",];
occupations["Kaylee"] = "";
occupations["Jayne"] = "Public Relations";
print(occupations);
print("n");

/**
* Create an empty array or dictionary,use the initializer syntax.
*/
var emptyStringArray = [String]()
let emptyIntegerArray = [Int]()
var emptyDictionary = [String : Double]()

emptyStringArray.append("I'm append")
print(emptyStringArray)

emptyDictionary["price"] = 21.00
print(emptyDictionary)

var carList = []
var studentInfo = [:]
carList = emptyStringArray
print(carList)
studentInfo = emptyDictionary
print(studentInfo)

var optionalString: String? = "hello"
print(optionalString == nil)
// you should notice,keyword nil is equal to null.

var optionalName: String? = "John Applseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello,(name)"
}
print(greeting)

let nickName: String? = nil
let fullName = "John Appelseed"
let infomalGreetin1 = "Hi (nickName ?? fullName)"
let infomalGreetin2 = "Hi (nickName != nil ? nickName :fullName)"
print(infomalGreetin1)
print(infomalGreetin2)

// switch
let vegetable = "red pepper"
switch vegetable{
case "celery":
    print("Add some raisins and make ants on a log.")
    //    case "cucumber","watercress","red pepper":
    //        print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a sicpy (x)")
default:// Switch must be exhaustive,consider adding a default clause.
    print("Evertthing tastes good in soup.")
}

let interestingNumbers = [
    "Prime" : [2,3,4,5,6,7],"Fibonacci" : [1,1,2,0],"Square" : [3,44,55,2]
]

var largest = 0
// for-in
for (kind,numbers) in interestingNumbers{
    print(kind)
    print(numbers)
    for number in numbers{
        //print(number)
        if (number > largest){
            largest = number
        }
    }
}
print("The largest number is (largest)")

// while
var m = 0
while (m < 0){
    m += 1;
}
print(m)

// repeat-while like do-while in other program language.
var n = 0;
repeat{
    n += 1;
}while n < 0
print(n)

// using ..< to make a range.
var sum = 0
for i in 0..<10 {
    sum += i
}
print(sum)

sum = 0
for (var i = 0; i<10 ;i++) {
    sum += i
}
print(sum)

// use func to declare a function. use -> to separate the parameter names and types from the function's return type.
func greet(name : String,age : Int) -> String{
    return "Hello (name),your age is (age)"
}
print(greet("YiSong",age: 22))

// use a truple to make a compound value - for example,to return multiple values from a function. The elements of a tuple can be rither by name or by number.
func calculateStatistics(scores : [Int]) -> (min : Int,max : Int,sum : Int,average: Float){
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    var average: Float
    for score in scores{
        if score < min{
            min = score
        }
        if score > max{
            max = score
        }
        sum += score
    }
    average = Float(sum)/Float(scores.count)
    return (min,max,sum,average)
}
// print(calculateStatistics([66,78,90,45,70,98,88,69,58]))
let statistics = calculateStatistics([66,58])
print("min score: (statistics.min),max score: (statistics.1),sum score:(statistics.sum),average score:(statistics.average))")


// Functions can also take a variable number of argument,collecting them into an array

func sumOf (numbers: Int...) -> Int{
    var sum = 0
    for number in numbers{
        sum += number
    }
    return sum
}
print(sumOf())
print(sumOf(23,56,67,90))

// functions are first-class type. This means that a funxtion can return another function as its value.
func makeIncrementer() -> ((Int) -> Int){
    func addOne(number: Int) -> Int{
        return number + 1;
    }
    return addOne
}
print(makeIncrementer()(8))

// A function can take another function as one of its arguments.
func hasAnyMatches(list: [Int],condition: (Int) -> Bool) -> (isMatche: Bool,list: [Int]){
    var isMatche: Bool = false
    var lessThanTenList: [Int] = []
    
    for item in list{
        if condition(item){
            isMatche = true
            lessThanTenList.append(item)
        }
    }
    return (isMatche,lessThanTenList)
}
func lessThanTen(number: Int) -> Bool{
    return number < 10
}
var result = hasAnyMatches([20,34,12],condition: lessThanTen)
print(result.isMatche)
print(result.list)

// closure
var numbers = [22,33,55]
print(numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
}))
print(numbers.map({ number in 3 * number}))

// rewrite the closure to return zero for odd numbers
func isOddNumber(number: Int) -> Bool{
    return number % 2 == 0 ? false : true
}
print(numbers.map({ (number: Int) -> Int in
    if isOddNumber(number){
        return 0
    }else{
        return number
    }
}))

//When a closure is the only argument to a function,you can omit the parentheses entirely.
print(numbers.sort{ $0 > $1})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读