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,103,87,12]
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)
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)> = []
let images : Array<Strig> = ["B","^","V",">","<"]
func initGame() {
iv1.removeAll()
iv2.removeAll()
for _ in 0..<rows {
for _ in 0..<cols {
iv1.append("a")
iv2.append("a")
}
}
}
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 ----")
}
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]
}
}
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
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
}
else if(source.x==destination.x) {
for hewY in source.y...destination.y {
g[cols * newY + source.x) = color
}
}
e1se if(source.y==destination.y) {
for newX in source.x...destinaticn.x {
g[cols * aource,y + newX ] = sclor
}
}
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 ViewController:UIViewController {
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()
}
func initGame(){
group.removeA11()
for _ in 0..<rows {
for _ in 0..<cols {
group.append("0")
}
}
}
func display() {
for i in 0..<rows {
for j in 0..<cols {
print(group[i*cols+j], separator: " ", terminator: " ")
}
print()
}
}
func setObject(row:Int,col:Int,objectID: String) {
if row>=rows || col>=co1s {
return
}
group[row*cols+col] = objectID
}
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":
for — in 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
let rect = CGRect (x:10, y:10, width:300, height:30)let label = UILabel(frame:rect)
self.view.addSubview(label)
let label = UILabel()
label.frame = CGRect(x:10, y:90, width:300, height:30)
self.view.addSubview(label)
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"
label.text ="I am a label,I am a label,I am a label"
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
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.addSubview(button)
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)
func btnClick(_ sender : UIButton)
print("Wuwu~~,I am here now")
sender.isSelected =!sender.isSelected
}
3.UIImageView
let imageView =UIImageView(frame: imageViewRect) let img = UIImage(named: "checkedBtn.png") imageView.image = img
self.view.addSubview(imageView)
let imageView =UIImageView(frame: imageViewRect) let img = UIImage(named: "checkedBtn.png") imageView.image = img
self.view.addSubview(imageView)
imageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector (tapAction(tap:)))
imageView.addGestureRecognizer(tap)
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
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))
view1.frame = CGRect(x:0,y:100, width:100,height:100)
viewl.backgroundColor = UIColor.red
view2.backgroundColor = UIColor.green
view3.backgroundColor = UIColor.blue
viewl.center = CGPoint(x:80,y:200)
self.view.addSubview(view1)
self.view.addSubview(view2)
self.view.addSubview(view3)
self.view.bringSubview(toFront: view1)
view1.alpha = 0.5
view1.layer.cornerRadius = 10
view1.layer.borderWidth=2
view1.layer.borderColor = UIColor.red.cgColor
import UIKit
class ViewController:UIViewController {
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 ViewController:UIViewController {
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()
}