仓颉的变量与数据类型
基本类型
var a: Int64 = 12
var b: String = ""
var c: Float16 = 11.2
var d: Bool = true
var e: (Int16, String) = (3, "")
var f: Array<(String, Bool)> = [("",false)]
var g1 = 0..4 //0,1,2,3
var g2 = 0..=4 //0,1,2,3,4
var g3 = 0..4 : 2 //0,2
var g4 = 4..0 //啥也没有
struct类型
struct Goods{
var name: String
private var price: Int16
var quantity: Int16 = 0 //初值可有可无,类型要有
static var id: Int16 //静态元素必须要有
static init() {
id = 0
}
//init普通构造函数
public init(name: String, price: Int16) {
this.name = name
this.price = price
}
//可以有多个构造函数,但参数列表不能一样
// public init(name: String, price: Int16, quantity: Int16) {
// this.name = name
// this.price = price
// this.quantity = quantity
// }
//主构造函数
public Goods(name: String, price: Int16, quantity: Int16){
this.name = name
this.price = price
this.quantity = quantity
}
//静态函数,只操作静态元素
static public func updateId(){
id +=1
}
//成员函数
public func totalPrice(): Int16{
this.price*this.quantity
}
//mut允许修改元素,且不用于静态元素
public mut func changeQuantuty(newQuentity: Int16){
this.quantity = newQuentity
}
}
Goods实例和函数调用
var pen: Goods = Goods("pen", 3)
Goods.updateId()
pen.changeQuantuty(2)
var pay = pen.totalPrice()
更多推荐


所有评论(0)