我有一个结构,其中包含 #include<iostream>
#include<vector>
using namespace std;
const int MAX = 100000;
bool visited[MAX] = {0};
int intime[MAX];
int outtime[MAX];
int timer = 0;
void dfs(vector<vector<int>> graph, int v)
{
visited[v] = true;
timer++;
intime[v] = timer;
vector<int>::iterator it = graph[v].begin();
while (it!=graph[v].end()) {
if (visited[*it] == false)
{
dfs(graph, *it);
}
it++;
}
++timer;
outtime[v] = timer;
}
int main()
{
vector<vector<int>> graph;
graph[1].push_back(2);
graph[1].push_back(3);
graph[3].push_back(6);
graph[2].push_back(4);
graph[2].push_back(5);
graph[5].push_back(7);
graph[5].push_back(8);
graph[5].push_back(9);
system("pause");
}
,String
和Bool
中的一些元素,我们称之为Int
。我还有另一个叫Struct A
的结构。
Struct B
我有一个B数组,我想将A的值分配给B。示例数组;
FirstElement(columnId:1,value:“ name = myname”) SecondElement(columnId:2,value:“ surname = mysurname”) ThirdElement(columnId:3,value:“ age = 20”)
我可以获得具有以下扩展名的结构的所有属性;
Struct A{
let name: String
let surname: String
let age: Int
}
Struct B{
let columnId: Int
let value: String
}
获得所有属性后,我希望进行某种迭代。 我的问题是如何在“ classA [i]”下方获取值和键,例如“ value = key”字符串
extension Loopable {
func allProperties() throws -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
// Optional check to make sure we're iterating over a struct or class
guard let style = mirror.displayStyle, style == .struct || style == .class else {
throw NSError()
}
for (property, value) in mirror.children {
guard let property = property else {
continue
}
result[property] = value
}
return result
}
}
编辑:我想在Struct A中获取所有具有其值的属性,并在创建Struct B对象时将其用作String作为value属性。
答案 0 :(得分:1)
修改您的setArray函数
func setArray(){
let keysArray = Array(classA.keys)
let valuesArray = Array(classA.values)
let classA = classA().getAllProperties()
for i in 0..<deviceLogs.count{
let valueString = keysArray[i] + "=" + valuesArray[i]
myArray.append(B(columnId: i, value: valueString) )
}
}
答案 1 :(得分:0)
看看这个
struct B {
let columnId: Int
let value: Any
}
protocol Properties {
var allProperties: [Any] { get }
}
extension Properties {
var allProperties: [Any] {
return Mirror(reflecting: self).children.flatMap { $0 }
}
}
struct A: Properties {
let name: String
let surname: String
let age: Int
}
以下是如何使用它的示例:
let properties = A(name: "name", surname: "surname", age: 18).allProperties
//注意:您在value
中的B
属性应为Any
类型,而不是String
var list = [B]()
for (index, property) in properties.enumerated() {
list.append(B(columnId: index, value: property))
}