Skip to content

数组与模型

数组 类型保存单一元素类型的有序、从零开始索引的值序列。 通过将元素类型包裹在 [ 和 ] 方括号中来书写:

[int]
[string]
[{ a: int, b: string }]
[[int]]
slint

元素类型可以是任何类型,包括结构体类型和另一个数组类型。

数组类型的值是一个模型:for 元素迭代的就是它。 数组类型的属性和数组字面量都充当模型。 原生代码也可以为数组属性提供模型实现,相同的操作作用于其上。

数组字面量将其元素列在 [ 和 ] 之间,以逗号分隔:

export component Example {
in-out property<[int]> list-of-int: [1, 2, 3];
in-out property<[{a: int, b: string}]> list-of-structs: [{ a: 1, b: "hello" }, { a: 2, b: "world" }];
}
slint

每个元素必须具有数组的元素类型。 空字面量 [] 是没有元素的模型。

以下操作适用于数组类型的值。

  • array.length 以 int 读取元素数量。 它是只读的;不能被赋值。
  • array[index] 读取从零开始的 index 处的元素。 索引是 int。
  • array[index] = value 写入 index 处的元素。 该数组在该上下文中必须可写。
  • array.push(value) 将 value 追加为新的最后一个元素。 value 必须具有元素类型。
  • array.remove(index) 移除 index 处的元素。
  • array.insert(index, value) 将 value 插入到 index 处的元素之前,将后面的元素后移。 value 必须具有元素类型。

length、push、remove 和 insert 是数组的成员;index 用 [ ] 运算符书写。

在当前边界之外的访问不会引发错误;每个操作定义自己的结果。

  • array[index] 当 index < 0 或 index >= array.length 时返回元素类型的默认值。
  • array[index] = value 当 index < 0 或 index >= array.length 时什么都不做。
  • array.remove(index) 接受 0 <= index < array.length。 任何其他 index 都不会改变数组。
  • array.insert(index, value) 接受 0 <= index <= array.length,因此在 array.length 处插入即追加。 任何其他 index 都不会改变数组。
export component Example {
in-out property<[int]> list-of-int: [1, 2, 3];
out property <int> len: list-of-int.length; // 3
out property <int> first: list-of-int[0]; // 1
out property <int> past-end: list-of-int[5]; // 0, the default int
init => {
// Both do nothing; list-of-int still holds [1, 2, 3].
list-of-int.remove(4);
list-of-int.insert(4, 10);
}
}
slint

© 2026 SixtyFPS GmbH