Swift学习笔记——函数、方法,属性
函数、方法,属性从本节开始将叙述swift函数,方法,属性等特性。
func someFunction(parameters) -> returnType{
// 函数主体
}
值得注意的是,函数支持多重返回,即返回多个值: func minMax(array: [Int]) -> (min: Int,max: Int) {
var currentMin = array[0]
var currentMax = array[0]
for value in array[1..<array.count] {
if value < currentMin {
currentMin = value
} else if value > currentMax {
currentMax = value
}
}
return (currentMin,currentMax)
}
在 Swift 中,使用函数类型就像使用其他类型一样。例如,你可以定义一个类型为函数的常量或变量,并将函数赋值给它。下面的代码是指定了一个函数类型的变量。这个变量其实就是addTwoInts的另一种形式。有点类似了 typealias. var mathFunction: (Int,Int) -> Int = addTwoInts
// 实例方法
class Counter {
var count = 0
func increment() {
++count
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
let counter = Counter()
// 初始计数值是0
counter.increment()
// 计数值现在是1
counter.incrementBy(5)
// 计数值现在是6
counter.reset()
// 计数值现在是0
// 类型方法
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
SomeClass.someTypeMethod()
struct Point {
var x = 0.0,y = 0.0
}
struct Size {
var width = 0.0,height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX,y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0,y: 0.0),size: Size(width: 10.0,height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0,y: 15.0)
print("square.origin is now at ((square.origin.x),(square.origin.y))")
// 输出 "square.origin is now at (10.0,10.0)”
对比三者,我们可以见到发现,其实函数和方法本就一体,个人感觉Swift这点比较冗余,其实这几出来直接叫方法(函数也可以)更好,更容易让人接受。函数多返回值和函数类型的使用将带来很大的便利。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 正则表达式分析工具
- oracle占比函数ratio_to_report
- NSJSONSerialization-JSON数据与NSDictionary和NSArray之间
- objective-c – 如何将依赖关系注入iOS视图控制器?
- c – 为什么我使用fprintf在这个C代码中收到警告?
- ruby-on-rails – 如何在Heroku上更改默认请求时间?
- ruby-on-rails – 在Cucumber Ruby上测试HTTP和HTTPS
- sqlite 数据库增加 createdStamp, LastUpdatedStamp 列 (默
- Flash教程1000例
- React-native – 使用base64的文件路径填充图像