编辑代码

var myString = "Hello world!     -  swift.jsrun.net"
print(myString)
let implicitInteger=70
let implicitDouble=70
let explicitDouble:Double=70
let label = "The width is"
let width = 94
let widthLabel = label + String (width)
let apples = 3
let oranges = 5
let appleSummary = "I have \ (apples) apples."
let fruitSummary = "I have \ (apples + oranges) pieces of fruit."
var shoppingList = ["catfish", "water","tulips","blue paint"]
shoppingList [1] = "bottle of water"

var occupations = [
"Malcolm": "Captain",
"Kaylee":"Mechanic",
]
occupations I" Jaynem] = mPublic Relations"

let emptyArray = [String] ()
let emptyDictionary = [String: Float] ()
shoppingList = []
occupations =[:]
let individualscores = [75,43,1038712]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
    teamScore += 1
} 
}
print (teamScore)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \ (name)"
}
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \ (nickName ?? fullName)"
let vegetable = "red pepper"
switch vegetable {
case "celery":
  print ("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
  print ("That would make a good tea sandwich.")
case let x where x. hasSuffix ("pepper"):
  print ("Is it a spicy \(x)?")
default:
print ("Everything tastes good in soup. ")
}
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square":[1, 4, 9, 16, 25],
]
var largest =0
for (kind, numbers) in interestingNumbers {
for number in numbers{
if number > largest{
largest = number
     }
  }
}
print(largest)
var n = 2
while n< 100{
   n=n* 2
}
Print (n)

var m = 2
repeat {
m = m * 2
}While m < 100
print (m)
var total = 0
for i in 0.. <4 {
totaL t+= i
}
print(total)
func greet (name: String, day: String) -> String {
     return "Hello \ (name), today is \ (day)."
}
greet ("Bob", day: "Tuesday")
 func greet (name: String ,day:String) -> String {
      reture "Hello \(name), today is  \(day)."
 }
 greet ("Bob", day: "Tuseday")

 func calculateStatistics (scores: [Int] )-> (min: Int,max: Int, sum: Int){
     var min =scores[0]
     var max =scores[0]
     var sum =0

     for score in score {
          if score >max{
              max = score
          }else if score<min{
              min = score
          }sum  += score
     }
     sum += score
 }
 reture (min,max,sum)
 }
 let statistics = calculateStatistics([5,3,100,3,9])
 print (statistics.sum)
 print(statistics.2)

func sumof (numbers: Int...) -> Int l
    var sum=0
    for number in numbers 
    sum += number
    }
return sum
}
sumof()
sumOf (42,597,12)

 func returnFifteen()-> Int {
   var y = 10
   func add() {
   y += 5
}
add()
return y
}
returnFifteen()

func makeIncrementer() -> (Tnt -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    reyurn addOne
}
var increment = makeIncrementer()
increment(7)*/

func hasAnyMatches (list: [Int], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
class Shape {
     var numberOfSides =0
     func  simpleDescription () -> String {
         return "A shape with \(numberOfSides) sides."
     }
}

var shape =Shape()
shape.numberOfSides =7
var simpleDescription =shape.simpleDescription()

class NamedShape {
    var numberOfSides: Int =0
    var name: String 

    init (name :String){
         self.name =name
    } 
    funce simpleDescription () ->String{
        return "A shape with \(numberOfSides) sides."
    }
}

class Square: NamedShape {
    var sideLwngth: Double

    init(sideLength: Double, name: String){
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 4
    }
    func area() -> Double {
        return sideLength * sideLength
    }
    override func simpleDescription() -> String{
        return "A square with sides of length \(sideLength)."
    }
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
teat.simpleDescription()

class EquilateralTriangle: NamedShape {
    var sideLength: Double- 0.0


    init(sideLength: Double, name:String) {
        self.sideLength-sideLength
        super.init(name:name)
        numberOfsides-3
        }
        
        var perimeter: Double {
            get {
                return 3.0 *sideLength
                }
                set {
                    sideLength=newValue / 3.0
                }
            }
        override func simpleDescription() -> String {
            return "An equilateral triagle with sides of length \(sideLength)."
            }
}

var triangle=EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(trianqle.sideLength)

calss TriangleAndSquare {
    var triangle: EquilateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    int(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EquilateralTriangle(sideLength: size, name: name)
    }
}
var triangleAadSquare = TriangleAadSquare(size: 10, name: "another test shape")
print(triangleAadSquare.square.sideLength)
print(triangleAadSquare.triangle.sideLength)
triangleAadSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAadSquare.triangle.sideLength)

enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() ->String {
        switch self {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "King"
        default:
           return String(self.rawValue)
        }
    } 
}
let ace = Rank.Ace
let aceRawValue = ace.rawValue

enum Suit {
    case Spades, Hearts, Diamonds, Clubs
    func simpleDescription() -> String {
        switch self {
            case .Spades:
                return "spades"
            case .Hearts:
                return "hearts"
            case .Diamonds:
                return "diamonds"
            case .Clubs:
                return "clubs"
        }
    }
}
let hearts = Suit.Hearts
let heartsDescription = hearts.simpleDescription()

struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() ->String{
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpads = Card(rank: .Three, suit: .Spades)
let threeOfSpadsDsecription = threeOfSpads.simpleDescription()

enum ServerResponse {
    case Result(String, String)
    case Failure(String)
}

let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Failure("Out of cheese.")

switch success {
case let .Result(sunrise, sunset):
     let ServerResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Failure(message):
    print("Failure... \(message)")
}

protocol ExampleProtocol {
    var simpleDescription: String {get}
    mutaing func adjust()
}

class SimpleClass: ExampleProtocol {
    var simpleDescription: String = "A very simple calss."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += " Now 100% adjusted."
    }
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription

struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple structure"
    mutating func adjust() {
        simpleDescription += " (adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }7
}
print(7.simpleDescription)

let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty)  // Uncomment to see the error

var myString = "Hello world!     -  swift.jsrun.net"
print(myString)
func findMonkey()->(Int,Int,String) (
for i in 0..<rows
for jin 0..<cols (
let value = group[i*cols+j]
switch value(
case "^":
return (i,j,"up")
case "v":
return(i,j,"down")
case "<"return(i,j,"left")
case ">":
inator
return(i,j,"right")
default:
这个 print()
)
)
) 
return(0,0, "none")
1

//数据定义部分
//定义行数和列数
let rows = 9
let cols = 5
//定义干扰项数量
let distractorMount = 5
//定义不同项数量
let differentMount = 3
//定义上下两个图形数组
var iv1 : Array<Strig> = []
var iv2 : Array<Strig> = []
//定义上下相同的干扰项数组
var cords : Array<(Int,Int)> = []
//定义上下不同的数组
var errorCords : Array<(Int,Int)> = []
//干扰项和不同项只能是B,^,v,>,<
let images : Array<Strig> = ["B","^","V",">","<"]
//数据定义结束

//函数1:初始化图形
func initGame() {
    iv1.removeAll()
    iv2.removeAll()
    for _ in 0..<rows {
        for _ in 0..<cols {
            iv1.append("a")
            iv2.append("a")
        }
    }
}

//函数2:显示
func display(){
    print("up image begin-----")
    for i in 0..<rows {
        for j in 0..<cols {
            print(iv1[i*cols+j],separator: " ", terminator: " ")
        }
        print()
    }
    print("up image end------")
    print("down image begin----")
    for i in 0..<rows {
        for j in 0..<cols {
            print(iv2[i*cols+j],separator: " ", terminator: " ")
        }
        print()
    }
    print("down image end ----")
}

//函数3:生成干扰项的随机位置和随机内容。
func distractorCerte(mount:Int){
    for _ in o..mount {
        let col = Int(arc4random()) % cols
        let row = Int(arc4random()) % rows
        cords.append(row,col)
        iv1[cols*row + col] = images[index]
        iv2[cols*row + col] = images[index]
    }
}

//函数4:生成不同项的随机位置和随机内容。
func differenceCreate (mount: Int) {
    for_in 0.. ‹mount{
        let cOl= Int (arc4random ()) % cols
        let row =Int (arc4random () )% rows

        errorCords.append ((row, col))
        /从images提供的宇符中选择一
        let index=Int (arc4random () ) % images.count
        /选择上面因形,还是下面图形?
        let which=Int (arc4random () ) %2
        //影响 iv1 和iv2这两个图形
        if which == 0{
            iv1 [cols*row+col] =images [index]
        }
        else{
            iv2 [cols*row +col] =images[index]
        }
    }
}
let rows = 20
let cols = 20
var q : Array<String>=[]

func gameInit (color: String){
    for_in 0..<rows {  
        for_in 0. .<cols{
            g.append (color)
        }
    }
}
func display () {
    for i in 0.. ‹rows {
        for j in 0..<cols {
            print (g[i*cols+j],separator: ""terminator: "")
        }
        print ()
    }
    print ("-------分割线-------")
}
func adaLine (source: (x: Int, y: Int), destination: (x: Int, y: Int) , color: String){
    //两个端点重合
if (source==destination){
    return
 }

//两个端点的X坐标相等。
else if(source.x==destination.x) {
    for hewY in source.y...destination.y {
        g[cols * newY + source.x) = color
    }
}


//两个端点的y坐标相等。
e1se if(source.y==destination.y) {
    for newX in source.x...destinaticn.x {
        g[cols * aource,y + newX ] = sclor
    }
}

//起始点的X坐标大于终点的x坐标。
else if (sourve.x<destination.x) {
    var dx:Float = 0, dy:Float = 0
    var newY : Float = 0
    var k : Float = 0

    dx = Float (destination.x - source.x)
    dy = Float (destination.y - source.y)
    k = dy / dx
    newY = Float(source.y)

    for x in source.x...destination.x{
        g[cols * Int(round(Double(newY))) + x] = color
        newY += k
    }
}
else {
    let nDestination = source
    let nSource = destination

    var dx:Float = 0, dy:Float = 0
    var newY : Float = 0
    var k : Float = 0

    dx = Float(nDestination.x - nSource.x)
    dy = Ploat(nDestination.y - nSource.y)
    k = dy / dx
    newY = Float(nSource.y)

        for x in nSource.x...nDestination.x {
            g[cols * Int(round(Double(newY))) + x] = color
            newY += k
        }
    }
}
//调试程序开始
gameInit(color:"——")
display()
ddaLine(source: (2,3), destination: (17,12) , color: "*")
display()
//结束
import UIKit
class ViewControllerUIViewController {
let rows = 9
let cols = 5
var group : Array<String> = []

override func viewDidLoad() {
super.viewDidLoad()
initGame ()
setObject(row: 4, col: 3, objectID: "y")
setObject(row: 3, col: 1, objectID: "B")
setobject(row: 6, col: 2, objectID: "B")
display()
}


//函数1:初始化函数
func initGame(){
   group.removeA11()//用于清除数组
   for _ in 0..<rows {
     for _ in 0..<cols {
        group.append("0")
       }
     }
}


//函数2:显示
func display() {
    for i in 0..<rows {
        for j in 0..<cols {
            print(group[i*cols+j], separator: " ", terminator: " ")
        }
        print()
    }
}

//函数3:添加一个物体
func setObject(row:Int,col:Int,objectID: String) {
    if row>=rows || col>=co1s {
        return
    }
    group[row*cols+col] = objectID
}

//函数4:查找猴子所在位置和状态
func findMonkey()->(Int,Int,String)
    for i in 0..<rows {
        for j in 0..<cols { 
            let value = group[i*cols+j]
            switch value {
            case "^":
                return(i,j,"up")
            case "v":
                return(i,j,"down")
            case "<":
                return(i,j,"left")
            case ">":
                return(i,j,"right")
            default:
                print()
            }
        }
    }
    return(0,0, "none")
}

//猴子转向
func turn(direction:String){
    let (row,col, status) = findMonkey ()
    if direction== "left" {
        switch status {
        case "up":
           group[row*cols+col] = "<"
        case "down":
           group[row*cols+col] = ">"
        case "left":
           group[row*cols+col] = "v"
        case "right":
           group[row*cols+col] = "^"
        default:
            print()
        }

    }
else if direction=="right" {
     print(row,col,status)
     switch status { 
     case "up":
        group[row*cols+col] = ">"
     case "down":
        group[row*cols+co1] = "<"
     case "left":
        group[row*cols+col] = "^"
     case "right":
        group[row*cols+co1] = "v"
     default:
         printn()
    }
    }
}

func step(steps:Int) {
   var (row,col,status) = findMonkey()
   switch status {
    case "up":
        for _ in 0..<steps {
            if row > 0 {
                group[row*cols+col]="|"
                row -= 1
                group(row*cols+col]="^"
            }
        }
    case "down":
        for _ in 0..<steps {
           if row < rows-1 {
                group[row*cols+co1]="|"
                row += 1
                group[row*cols+col]="v"
            }
        }
    case"left":
        for _ in 0..<steps {
            if col > 0 {
                group[row*cols+col]="-"
                col -= 1        
                group[row*cols+col]="<"
            }
        }
    case "right":
        forin 0..<steps {
            if col < cols-1 {
                 group [row*cols+col]="-"
                col += 1
                group[row*cols+col]=">"
            }
        }
        default:
            print()
        }
    }



//图形化显示程序
func displayBackgroundView() {
    let h = backgroundView.frame.size.height
    let w = backgroundView.frame.size.width

    let padding : CGFloat = 15
    let margin : CGFloat = 30
    //计算每个格子的高度和宽度
    let grid_w=(w-margin*2-padding*CGFloat(cols-1))/CGFloat(cols)
    let grid_h=(h-margin*2-padding*CGFloat(rows-1))/CGFloat(rows)

    for i in 0..<rows {
        for j in 0..<cols {
        let x = margin + CGFloat(j) * (grid_w + padding) 
        let y = margin + CGFloat (i) * (grid_h + padding) 
        let fect = CGRect (x: X, y:y, width: grid_w, height: grid_h)
        //用于根据数组中数值来决定显示哪个图片
        let data = group [i*cols+j]
        var fileName = ""
        switch data {
        case "0":
            fileName ="GreenBlock"
        case "B":
            fileName ="Banana"
        case "^":
            fileName ="Monkey_up"
        case "v":
            fileName ="Monkey_down"
        case "<":
            fileName ="Monkey_left"
        case ">":
            fileName ="Monkey_right"
        default:
            fileName = "GreenBlock"
        ) 
        let img = UIImage(named: fileName)
        let imgView = UIImageView(frame: rect)
        imgView.image = img
        self.backgroundView.addSubview(imgView)
        }
    }
}

/1.UILabel
//UILabel的代码创建方法
//方法 1:创建时设置 frame
let rect = CGRect (x:10, y:10, width:300, height:30)let label = UILabel(frame:rect)
//添加到 self.view 上才会显示出来
self.view.addSubview(label)
// 方法 2:先创建,后设置 frame
let label = UILabel()
label.frame = CGRect(x:10, y:90, width:300, height:30)
self.view.addSubview(label)

//显示多行文本
//方法 1: 显示固定行数的文本
label.frame = CGRect(x:10, y:100, width:100, height:100)label.numberOfLines = 2
label.text ="I am a label,I am a label,I am a label"
//方法2:根据文字长度自己确定显示几行,只需设置numberofLines=0label.numberOfLines = 0
label.text ="I am a label,I am a label,I am a label"

//UILabel的常用属性
//设置背景色
label.backgroundColor = UIColor.green
//设置字体颜色
label.textColor = UIColor.red
//设置字体大小
label.font = UIFont.systemFont(ofSize: 14)
//设置文本对齐方式,默认左对齐
label.textAlignment = NSTextAlignment.right
//设置要显示的文本
label.text = "I am a label"
//当文字超出标签宽度时,自动调整文字大小,使其不被截断
label.adjustsFontSizeToFitWidth = true

2.UIButton
//UIButton的代码创建方法
// 方法 1:创建一个系统内建样式的UIButton
let button = UIButton(type: UIButtonType.system)
button.frame = CGRect(x:150,y:150, width:120, height:40)
button.setTitle("Click me", for: UIControlState.normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.addTarget(self, action: #selector(btnClick(:)), for: UIControlEvents. touchUpInside)
button.layer.cornerRadius = 5.0
//添加到 self.view上才会显示出来
self.view.addSubview(button)
//方法2:创建一个自定义的UIButton,用于模拟复选框
let rect = CGRect(x:10, y:150, width:50, height:50)
let button = UIButton(frame:rect)
button.setImage (UIImage (named:"checknoneBtn.png"), for: UIControlState.normal)
button.setImage (UIImage (named:"checkedBtn.png"), for: UIControlState.selected)
button.addTarget(self, action: #selector(btnClick(_:)), for: UIControlEvents. touchUpInside)
button.layer.cornerRadius = 5.0
self.view.addSubview(button)
//Button 触摸后,需要调用的事件方法
func btnClick(_ sender : UIButton)
print("Wuwu~~,I am here now")
sender.isSelected =!sender.isSelected
}

3.UIImageView
//UIImageView代码创建方法
let imageView =UIImageView(frame: imageViewRect) let img = UIImage(named: "checkedBtn.png") imageView.image = img
//添加到self.view上才会显示出来
self.view.addSubview(imageView)
let imageView =UIImageView(frame: imageViewRect) let img = UIImage(named: "checkedBtn.png") imageView.image = img
//添加到self.view上才会显示出来
self.view.addSubview(imageView)
//UIImageVied交互功能w代码创建方法
//用户交互
imageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector (tapAction(tap:)))
imageView.addGestureRecognizer(tap)
//UIImageView触摸后,需要调用的事件方法
func tapAction(tap :UITapGestureRecognizer)
let scale :CGFloat = 1.2
var frame = tap.view!.frame
frame = CGRect(x:frame.origin.x, y:frame.origin.y, width:frame.size.width★scale, height:frame.size.height ★ scale)
tap.view!.frame = frame
}

4.UIView
//UIView的代码创建方法
//创建View
let viewl = UIView()
let view2 = UIView(frame: CGRect(x:20,y:120, width:100, height:100))let view3 = UIView(frame: CGRect(x:40,y:140, width:100,height:100))// 设置 view 的尺寸
view1.frame = CGRect(x:0,y:100, width:100,height:100)
//设置view的背景色
viewl.backgroundColor = UIColor.red
view2.backgroundColor = UIColor.green
view3.backgroundColor = UIColor.blue
//设置view的中心位置,不改变view的大小
viewl.center = CGPoint(x:80,y:200)
//依次添加三个视图(从上到下是:蓝,绿,红)
self.view.addSubview(view1)
self.view.addSubview(view2)
self.view.addSubview(view3)
//把view1(红)移到最上面
self.view.bringSubview(toFront: view1)
//设置view的透明度
view1.alpha = 0.5
//设置view1的圆角角度
view1.layer.cornerRadius = 10
//设置边框的的宽度
view1.layer.borderWidth=2
//设置边框的颜色
view1.layer.borderColor = UIColor.red.cgColor
import UIKit
class ViewControllerUIViewController {
let rows = 9
let cols = 5
var group : Array<String> = []

override func viewDidLoad() {
super.viewDidLoad()
initGame ()
setObject(row: 4, col: 3, objectID: "y")
setObject(row: 3, col: 1, objectID: "B")
setobject(row: 6, col: 2, objectID: "B")
display()
}
import UIKit
class ViewControllerUIViewController {
let rows = 9
let cols = 5
var group : Array<String> = []

override func viewDidLoad() {
super.viewDidLoad()
initGame ()
setObject(row: 4, col: 3, objectID: "y")
setObject(row: 3, col: 1, objectID: "B")
setobject(row: 6, col: 2, objectID: "B")
display()
}