前端之家收集整理的这篇文章主要介绍了
swift-学习之路,字典、数组、循环-控制流,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
//
// ViewController.swift
// UIWindow
import UIKit
import Foundation
class ViewController: UIViewController {
@IBOutlet weak var usrNameLabel: UITextField!
@IBOutlet weak var passwdLabel: UITextField!
@IBAction func btnTouch(sender: AnyObject) {
println("usrName is \(self.usrNameLabel.text)");
println("passwdLabel is \(self.passwdLabel.text)");
}
override func viewDidLoad() {
super.viewDidLoad()
println("Hello World");
let label = "The width is"
let width = 90
let widthLabel = label + String(width)
println("widthLabel is \(widthLabel)")
var shoppingList = ["catfish","water","tulips","blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm":"Captain","Kaylee":"Machanic",]
occupations["Jayne"] = "Public Relation"
//初始化一个空的数组
let emptyArray = [String]()
//初始化一个空的字典
let emptyDictionary = [String : Float]()
let individualscores = [75,43,103,87,12]
var teamscore = 0
//循环语句的使用
for score in individualscores{
if(score > 50)
{
teamscore += 3
}
else
{
teamscore += 1
}
}
print(teamscore)
var optionalString:String? = "Hello"
optionalString == nil
var optionalName:String? = "John Appleasee"
var greeting = "Hello"
/*if let name = optionalName{
greeting = "Hello,\(name)"
}
*/
//如果可选值为nil 则不会执行代码块的内容
/*
optionalName = nil
if let name = optionalName{
greeting = "Hello \(name)"
}
print(greeting)
*/
optionalName = nil
if let name = optionalName{
greeting = "Hello \(name)"
}else{
greeting = "-执行的第二句代码-"
}
print(greeting)
/**
switch 支持任意类型的数据以及各种比较操作-不限于整数和表达式
// 不需要加break
*/
let vegetable = "red pepper"
switch vegetable{
case "celery":
let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber","watercress":
let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy\(x)?"
default:
let vegetableComment = "Everything tastes good in soup."
}
/// 这里用于比较字典中的最大值并且把变量是哪种类型的输出来
let interestingNumbers = [
"Prime":[2,3,5,7,11,13],"Fibonacci":[1,1,2,8],"Square":[1,4,9,16,25],]
var largest = 0
var name:String?
for (kind,numbers) in interestingNumbers{
for number in numbers{
if number > largest{
largest = number
name = kind
}
}
}
println(largest)
println(name)
/**
1+2+....+100;
*/
//这里用起来十分的方便,程序不运行会有提示,可以试试如果i的值不++ 可以观察一下
var sum = 0
var i = 0
while i <= 100{
sum += i
i++
}
print(sum)
/**
..< 和 ... 表示范围
..< 不包含上届 ...包含上届
*/
var firstForLoop = 0
for i in 0..<3{
firstForLoop += i
}
print(firstForLoop)
var secondForLoop = 0
for var i = 0;i < 3; ++i{
secondForLoop += i;
}
print(secondForLoop)
//self.usrNameLabel.
// Do any additional setup after loading the view,typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
原文链接:https://www.f2er.com/swift/326256.html