值绑定 and 区间运算符 and where

本文通过示例介绍了Swift中的值绑定与区间运算符的使用方法,包括for-in循环结合区间运算符遍历数组元素,以及在if、guard、switch语句中使用值绑定进行模式匹配。

源代码:

//
//值绑定   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)")
}
运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值