//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
//1
let normalVar:Float = 4
//2
let label = "The width is"
let width = 66
let widthLabel = label + String(width)
//3
let aFloat = 1.2
let bFloat = 2.2
print("The sum is \(aFloat + bFloat) Hello,\("Sally")")
//4
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName:String? = nil
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello,\(name)"
}else{
greeting = "name is nill"
}
/*
当可选值为nil时,不进行赋值,跳过代码
*/
//5
let interestingNumbers = [
"A" : [2,3,5,7,11,13],
"B" : [1,1,2,3,5,8],
"S" : [1,4,9,16,25]
]
var largest = 0
var largestKind:String = ""
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
largestKind = kind
}
}
}
print(largest,largestKind)
//6
//下划线表示参数名可省略
func greet(name:String, eat:String)->String{
return "\(name) eat \(eat) today"
}
greet(name: "Sally", eat: "potato")
//7.计算参数平均值
//函数带可变个数的参数,在函数内部表现为数组的形式
func Average(numbers:Int...) ->Int{
var sum = 0
var count = 0
for number in numbers {
sum += number;
count += 1;
}
return sum/count;
}
Average(numbers: 1,2,3,4,5)
//8.闭包 对所有奇数返回0
var numbers = [20,19,7,12]
let numbersHasOdd = numbers.map({
(num:Int)-> Int in
if num % 2 == 1{
return 0;
}
return 1;
})
print(numbersHasOdd)
//9 创建namedShape的另一个子类Circle,构造器接收两个参数,一个是半径一个是名称,在子类Circle中实现area() 和 simpleDescription参数
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Circle : NamedShape{
var radius:Double = 0
init(name: String, radius:Double) {
self.radius = radius
//初始化父类
super.init(name: name)
}
func area(radius:Double) -> Double {
self.radius = radius
return 3.14 * radius * radius
}
override func simpleDescription() -> String {
return ("This circle's area is \(area(radius: radius))")
}
}
var namedClass = NamedShape(name: "Named")
var cirArea = Circle(name:"Circle",radius:1)
cirArea.area(radius: 2)
cirArea.simpleDescription()
//10、写一个函数,通过比较它们的原始值来比较Rank值
enum Rank: Int{
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queue, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
func isLarger(_ para1:Rank, para2:Rank) -> Bool{
if para1.rawValue > para2.rawValue {
return true;
}
return false;
}
isLarger(.Four, para2: .Three)
Swift官方文档 部分练习题解
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 整理和总结官方文档的中文翻译版上面对于Redux-sage的介绍文档地址:http://leonshi.com/r...
- 构建项目一般在spring的官网https://projects.spring.io/spring-boot/快速...
- 陈慧珊、宣萱、蔡少芬和郭可盈并称TVB90年代四大花旦,陈慧珊和其他三位相比,出道最晚,却是上位最快的一位,同时还...