Swift中的函数常见写法


这里不涉及函数作为参数和返回值的情况。

进军iOS开发了哈。

计划六一前,搞一个套H5的App出来,

靠谱么?


其实,看过了java,php,javascript,python,go之后,

再在看swift,感觉很亲切啊,

都是老熟人。


func greet(person: String) -> String {
	let greeting = "Hello, " + person + "!"
	return greeting
}

print(greet(person: "Anna"))
print(greet(person: "Brian"))

func sayHelloWorld() -> String {
	return "hello, world"
}

print(sayHelloWorld())

func greet2(person: String) {
	print("Hello, \(person)!")
}

greet2(person: "Dave")

func printAndCount(string: String) -> Int {
	print(string)
	return string.characters.count
}

func printWithoutCounting(string: String) {
	let _ = printAndCount(string: string)
}

printAndCount(string: "Hello, world")
printWithoutCounting(string: "Hello, world")


func minMax(array: [Int]) -> (min: Int, max: Int)? {
	if array.isEmpty {return nil}
	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)
}

if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
	print("min is \(bounds.min) and max is \(bounds.max)")
}

func gt(person: String, from hometown: String) -> String {
	return "Hello \(person)! glad you could visit from \(hometown)."
}

print(gt(person: "Bill", from: "Cupertino"))


func someFunc(_ firstP: Int, secondP: Int) {
	print(firstP + secondP)
}

someFunc(1, secondP: 5)

func someFunc2(pWithoutD: Int, pWithD: Int = 12) {
	print(pWithoutD + pWithD)
}

someFunc2(pWithoutD: 5)

func arithmeticMean(_ numbers: Double...) -> Double {
	var total: Double = 0
	for number in numbers {
		total += number
	}
	return total / Double(numbers.count)
}

print(arithmeticMean(1, 2, 3, 4, 5))
print(arithmeticMean(3, 5.34, 12.38, 67, 21.97))

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
	let temporaryA = a;
	a = b
	b = temporaryA
}

var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")



	


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值