swift基础语法

前言

使用flutter期间 ,但是还是用到一些原生的,学习一些ios的基础用法。学习自 swift教程 ,里面有一些代码的问题,在文章里纠正了。

  1. 首先在xcode中建一个playground,这个文件类似一个编辑器,方便学习语法


  2. 点击左边的运行按钮,右边可以看到结果,有点类似调试的感觉。


  3. 学习的基本语法,playground内容
import UIKit
//-----------------字符串------------------------
var greeting = "Hello, playground"
let label = "The width is "
let width :Double = 94
let widthLabel = label + String(width)//"The width is 94.0"
let apples = 3
let oranges =  Int("5") ?? 0//5
let optionalInt: Int? = 0
let appleSummary = "I have \(apples) apples."//"I have 3 apples."
/**
 oranges为非空的情况,就不可以加!,oranges为可空的情况,加!也没用,因为系统编译会检查出无法保证有值。类似把optionalInt的默认值去掉,加!也会报错。
 */
let fruitSummary = "I have \(apples + oranges + optionalInt! ) pieces of fruit."//"I have 8 pieces of fruit."

//------------------------数组------------------------
var ratingList = ["Poor", "Fine", "Good", "Excellent"]//Array of 4 String elements
ratingList[1] = "OK"
print(ratingList)//"["Poor", "OK", "Good", "Excellent"]\n"
let emptyArray = [String]()//Array of 0 String elements

//------------------------控制流if------------------------
let number = 23
if number < 10 {
    print("The number is small")
} else if number > 100 {
    print("The number is pretty big")
} else {
    print("The number is between 10 and 100")
}

//在if语句中使用可选绑定来检查可选类型是否有值。
var optionalName: String? = "swift"
var greetings = "Hello!"
if let name = optionalName {
    greetings = "Hello, \(name)"//"Hello, swift"
} else{
    greetings = "nobody"
}

//if let 语句中添加更复杂的条件判断逻辑,就需要按照正确的语法使用逗号进行分隔,来依次罗列各个绑定和条件判断内容。相当于&
var optionalHello: String? = "Hello"
if let hello = optionalHello, hello.hasPrefix("H"), let name = optionalName {
    greeting = "\(hello), \(name)"//"Hello, swift"
}

//------------------------switch------------------------
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)?"//"Is it a spicy red pepper?"
default:
    let vegetableComment = "Everything tastes good in soup."
}

//------------------------轮询------------------------
var firstForLoop = 0
for i in 0..<4 {
    firstForLoop += i//6
}
print(firstForLoop)//"6\n"

var secondForLoop = 0
for _ in 0...4 {
    secondForLoop += 1//5
}
print(secondForLoop)//"5\n"

//------------------------函数------------------------

//->返回类型
func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."//"Hello Anna, today is Tuesday."
}
greet(name: "Anna", day: "Tuesday")//"Hello Anna, today is Tuesday."

//如果像省略第一个参数名
func greet(_ name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."//"Hello Anna, today is Tuesday."
}
greet("Anna", day: "Tuesday")//"Hello Anna, today is Tuesday."

var array = ["apple", "banana", "dragonfruit"]//Array of 3 String elements
array.insert("cherry", at: 2)//Array of 4 String elements
print(array)//"["apple", "banana", "cherry", "dragonfruit"]\n"

//------------------------类------------------------
class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."//"A shape with 7 sides."
    }
}
var shape = Shape()//Shape
shape.numberOfSides = 7//Shape
var shapeDescription = shape.simpleDescription()//"A shape with 7 sides."

class NamedShape {
    var numberOfSides = 0
    var name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A \(name) with \(numberOfSides) sides."//"A my named shape with 0 sides."
    }
}
var namedShape = NamedShape(name: "my named shape")//NamedShape
namedShape.simpleDescription()//"A my named shape with 0 sides."

class Square: NamedShape {
    var sideLength: Double

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        numberOfSides = 4
    }

    func area() ->  Double {
        return sideLength * sideLength//27.04
    }

    override func simpleDescription() -> String {
        return "A square with sides of length \(sideLength)."//"A square with sides of length 5.2."
    }
}
let testSquare = Square(sideLength: 5.2, name: "my test square")//Square
testSquare.area()//27.04
testSquare.simpleDescription()//"A square with sides of length 5.2."

//可失败构造器
class Circle: NamedShape {
    var radius: Double

    init?(radius: Double, name: String) {
        self.radius = radius
        super.init(name: name)
        numberOfSides = 1
        if radius <= 0 {
            return nil
        }
    }

    override func simpleDescription() -> String {
        return "A circle with a radius of \(radius)."//"A circle with a radius of 4.2."
    }
}
let successfulCircle = Circle(radius: 4.2, name: "successful circle")//Circle
successfulCircle?.simpleDescription()//"A circle with a radius of 4.2."
let failedCircle = Circle(radius: -7, name: "failed circle")//nil
failedCircle?.simpleDescription()//nil

//------------------------类型转换------------------------
class Triangle: NamedShape {
    init(sideLength: Double, name: String) {
        super.init(name: name)
        numberOfSides = 3
    }
}
let shapesArray = [Triangle(sideLength: 1.5, name: "triangle1"), Triangle(sideLength: 4.2, name: "triangle2"), Square(sideLength: 3.2, name: "square1"), Square(sideLength: 2.7, name: "square2")]
var squares = 0
var triangles = 0
for shape in shapesArray {
    if let square = shape as? Square {
        squares+=1//2
    } else if let triangle = shape as? Triangle {
        triangles+=1//2
    }
}
print("\(squares) squares and \(triangles) triangles.")//"2 squares and 2 triangles.\n"

//------------------------枚举------------------------
enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, 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//.Ace
let aceRawValue = ace.rawValue//1
Rank.Jack.rawValue//11

if let convertedRank = Rank(rawValue: 3) {
    let threeDescription = convertedRank.simpleDescription()//"3"
}

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 //.Hearts
let heartsDescription = hearts.simpleDescription()//"hearts"

//------------------------简单地类-结构体------------------------
/**
 类和结构体之间最重要的一个区别是:结构体在代码中被传递时总是以复制的形式传递的,但是类是以引用传递的。结构体在定义轻量级的数据类型上是很完美的,它不需要有很多类似于继承和类型转换的功能。
 */
struct Card {
    var rank: Rank
    var suit: Suit
    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }
}
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()

//------------------------协议-可以理解为接口------------------------
//类似android的interface
protocol ExampleProtocol {
    var simpleDescription: String { get }
    func adjust()
}

protocol ExampleProtocol2 {
    var simpleDescription2: String { get }
}
//在simpleDescription属性之后的{ get }表示这是一个只读的属性,意味着这个属性的值只能获取,不能改变。

class SimpleClass: ExampleProtocol,ExampleProtocol2 {
    var simpleDescription: String = "A very simple class."
    var simpleDescription2: String = "A very simple class2."
    var anotherProperty: Int = 69105
    func adjust() {
        simpleDescription += "  Now 100% adjusted."
    }
}

var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription//"A very simple class.  Now 100% adjusted."

class SimpleClass2: ExampleProtocol {
    var simpleDescription: String = "Another very simple class."
    func adjust() {
        simpleDescription += "  Adjusted."
    }
}

var protocolArray: [ExampleProtocol] = [SimpleClass(), SimpleClass(), SimpleClass2()]
for instance in protocolArray {
    instance.adjust()
    print(instance.simpleDescription)//"Another very simple class.  Adjusted.\n"
}




后记

ui的基础在这里,dashboard ,no swiftui
ui搭建学习

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。