Swift入门基础语法

1.方法声明:

//( )里面声明2个int 类型参数。返回的参数类型写在->后面。如果有多个返回参数的话->( )

func incrementBy(amount: Int, times: Int) ->String

{
       count += amount * times  

       return "sum is \(count)."

}

counter.incrementBy(amount: 2, times: 7)

//number 和numberOfTimes 用来外部声明函数参数

func incrementBy(number amount: Int, numberOfTimes times: Int)

{
         count += amount * times
}

counter.incrementBy(number: 2, numberOfTimes: 7)

2.类声明:使用class和类名类创建一个类。类中属性的声明和常量、变量声明也是一样,唯一的区别就是它们的上下文是类。同样,方法和函数声明也是一样。

//声明变量的时候如果声明了类型,则需要初始化构造器不然会出错。如果直接声明:var name = "";这样不需要初始化构造器

class Shape {

    var name :String

    init(name: String){

        self.name = name  

    }

    func simpleDescription( ) -> String {

        return "A shape";

    }

}

var myShape = Shape(name: "NAME");

3.类重写:子类重写父类的方法的话,需要使用override重写父类的方法

class smallShape : Shape{

   override func simpleDescription()-> String{

   }

}

4.属性set与get方法:

var length: Int {

get {

return 3;

}

set {

length = newValue/3;

}

}

5.枚举和结构体:

使用enum来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法。

enum Rank :Int {

   case Ace =1

   case Two,Three

   func simpleDescripiton()-> String {

       switch self{

       case Rank.Ace,Rank.Three:

           return "Ace"

       case .Two

           return "Two"

       default:

           return "default"

       }

   } 

}

使用struct来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是结构体是传值,类是传引用

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()
6.接口和拓展:

使用protocol来声明一个接口(类,枚举和结构体都可以实现接口)

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

}

使用extension来为现有的类型添加功能,比如添加一个计算属性的方法。你可以使用扩展来给任意类型添加协议,甚至是你从外部库或者框架中导入的类型。

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

}}







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值