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搭建学习

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,837评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,551评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,417评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,448评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,524评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,554评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,569评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,316评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,766评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,077评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,240评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,912评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,560评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,176评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,425评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,114评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,114评论 2 352