Swift Basic

推荐使用Xcode6 playground的功能来测试,可以很方便看到输出

不需要分号

println("Hello, world!")

简单的赋值方式

使用 let 标记一个常量   var 标记一个变量

var myVariable = 42
myVariable = 50

let myConstant = 42

追加声明数据类型

let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70

变量之间可以方便的转换类型

let label = "The width is "
let width = 94
let widthLabel = label + String(width)

以 \(变量名) 的形式可以很方便的无视类型转换到String输出

let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."

创建数组,字典

var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"

初始化数组,字典

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

流程控制

if , switch 做流程选择

for-in, for, while, do-while 做循环控制

let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}
teamScore

好来分析一下下面的代码

//使用if和let来处理可能不存在的值
//在数据类型后面加?来标记可能不存在的值

var optionalString: String? = "Hello"
optionalString == nil
//如果optinalName 为nil 则执行else 
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, \(name)"
}else{
greeting="The value is nil"}
//定义字典
let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    //取出字典里面的数字
    for number in numbers {
        //挑选出最大的值
        if number > largest {
            largest = number
        }
    }
}
largest         //结果为25
  • for i in 0..<4
  • for var i = 0; i < 4; ++i

上面两个语句是等效的

------------------------------------------------

函数

Use func to declare a function. Call a function by following its name with a list of arguments in parentheses. Use -> to separate the parameter names and types from the function’s return type.

使用func定义一个函数

使用->设置函数返回数据类型

//传入参数2个String,返回一个String
func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}

//调用函数
greet("Li", "SUNDAY")
//传入参数是一个Int数组,函数功能算出这个数组的最大 最小 和值 
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    
    //初始化,将最小值,最大值定义到Int数组第一个值
    var min = scores[0]
    var max = scores[0]
    var sum = 0
   
   //遍历数组
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
   
    return (min, max, sum)
}
//调用函数  
let statistics = calculateStatistics([5, 3, 100, 3, 9])
statistics.sum
statistics.2
时间: 2024-08-29 04:54:44

Swift Basic的相关文章

Swift Basic 2

传入函数的参数可以简单的用一个数组动态传入 func sumOf(numbers: Int...) -> Int {     var sum = 0     for number in numbers {         sum += number     }     return sum } sumOf() sumOf(42, 597, 12) sumOf(222,3333,44444,555555) 函数可以嵌套使用 func returnFifteen() -> Int {     va

计算机基础篇之二

目录 1.1 编程语言 1)低级语言 2)高级语言 1.2 内核kernel 1.3 程序 1.4 进程 1.5 cpu内存空间 1.1 编程语言 1)低级语言 #离机器越近语言 #二进制机器指令 #汇编语言 #ADD,R0,R1,ST... 2)高级语言 #离近人类越近的自然语言 #编译型语言 #c,c++,go... #解释型语言 #c#,python,java,swift,basic... 1.2 内核kernel #是一个通用软件,运行在硬件上,不负责具体的工作,只是协调各个程序,将硬件

寒城攻略:Listo 教你 25 天学会 Swift 语言 - 03 The Basic

import Foundation //*********************************************************************************************** //1.The Basics(基础) //_______________________________________________________________________________________________ //介绍 //Swift 的类型是

寒城攻略:Listo 教你 25 天学会 Swift 语言 - 04 Basic Operators

import Foundation //*********************************************************************************************** //1.Basic Operators(基本操作符) //_______________________________________________________________________________________________ //简介 //操作

在Coxoa和Objextive-C中使用Swift(1)Basic Setup

在Coxoa和Objextive-C中使用Swift(Using Swift with Cocoa and Objective-C) 开始->基本设置 说明:这是一个针对API和开发技术的初步文件.苹果公司提供了这个文档帮助您选择合适技术和编程接口,来构建苹果品牌产品.这个信息使随时变化的,软件实施要根据本文在最终的操作系统软件和最终文件进行测试.本文档的较新版本可能提供关于新的API或技术的细节. Swift的设计提供了对Cocoa和Objective-c的无缝兼容.你可以在Swift中使用O

Swift学习笔记-基本运算符(Basic Operators)-求余运算符

求余运算(a % b)是计算b的多少倍刚刚好可以容入a,返回多出来的那部分(余数). 注意:求余运算(%)在其他语言也叫取模运算.然而严格说来,我们看该运算符对负数的操作结果,"求余"比"取模"更合适些. 我们来谈谈取余是怎么回事,计算9 % 4,你先计算出4的多少倍会刚好可以容入9中: 2倍,非常好,那余数是1(用橙色标出) 在 Swift 中可以表达为: 9 % 4 // 等于 1 为了得到a % b的结果,%计算了以下等式,并输出余数作为结果: a = (b

[Swift]LeetCode227. 基本计算器 II | Basic Calculator II

Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, /operators and empty spaces . The integer division should truncate toward zero. Example 1: Input: "3+2*2" Ou

swift语言点评三 - Basic Operators

1.Tuples are compared from left to right, one value at a time, until the comparison finds two values that aren't equal. (1, "zebra") < (2, "apple") You can compare two tuples if they have the same type and the same number of values.

[Swift]LeetCode770. 基本计算器 IV | Basic Calculator IV

Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as