源代码:
//
//值绑定 and 区间运算符.swift
//
// Created by chenzhen on 16/8/1.
// From 大连东软信息学院
// Copyright © 2016年 zhen7216. All rights reserved.
//
import Foundation
//for in and 区间运算符
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let count = numbers.count
print("**************")
for i in 0..<count {
print("第\(i + 1)个元素: \(numbers[i])")
}
print("**************")
for i in 0...5 {
print("第\(i + 1)个元素: \(numbers[i])")
}
print("**************")
//if中的值绑定
struct Blog {
let name: String?
let URL: String?
let Author: String?
}
func ifStyleBlog(blog: Blog) {
if let blogName = blog.name,
let blogURL = blog.URL,
let blogAuthor = blog.Author{
print("这篇博客名: \(blogName)")
print("这篇博客由 \(blogAuthor)写的")
print("这篇博客的网址: \(blogURL)")
} else {
print("这篇博客信息不完整!")
}
}
let blog1 = Blog(name: nil, URL: "chenzhen.com",Author: "chenzhen")
let blog2 = Blog(name: "chenzhen", URL: "chenzhen.com",Author: "chenzhen")
print("--blog1--")
ifStyleBlog(blog1)
print("--blog2--")
ifStyleBlog(blog2)
print("************")
//guard中的值绑定
func guardStyleBlog(blog: Blog) {
guard let blogName = blog.name,
let blogURL = blog.URL,
let blogAuthor = blog.Author else {
print("这篇博客信息不完整!")
return
}
print("这篇博客名: \(blogName)")
print("这篇博客由 \(blogAuthor)写的")
print("这篇博客的网址: \(blogURL)")
}
print("--blog1--")
ifStyleBlog(blog1)
print("--blog2--")
ifStyleBlog(blog2)
print("***************")
//switch中的值绑定
var student = (id:"1002", name:"lisi", age:32, ChineseScore:90, EnglishScore:91)
var desc: String
switch student {
case (_,_, let AGE, 90...100, 90...100):
if (AGE > 30) {
desc = "laoyou"
} else {
desc = "xiaoyou"
}
default:
desc = "wu"
}
print("说明: \(desc)")
print("***************")
//switch 中使用where语句
var student1 = (id:"1002", name:"lisi", age:20, ChineseScore:90, EnglishScore:91)
var desc1: String
switch student1 {
case (_,_, let AGE, 90...100, 90...100) where AGE > 20:
desc1 = "you"
default:
desc1 = "wu"
}
print("说明: \(desc1)")
print("******************")
//for-in中使用where语句
let numbers1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("---------------")
for item in numbers1 where item > 7 {
print("Count is: \(item)")
}
运行结果: