Swift结构项值不随函数而变化

时间:2018-06-18 23:37:20

标签: swift function struct

我有以下代码,但即使将函数newMethod(newName: String)添加到类中,username的值也不会因变量user而发生变化。 Profile结构在不同的类中定义。我究竟做错了什么?注意:我正在使用LBTAComponents窗格。

import LBTAComponents

class ProfileDatasource: Datasource {
    let placeholderIV: UIImageView = {
        let imageView = UIImageView()
        return imageView
    }()

    var user = Profile(username: String(), school: "fat", rating: 48, friends: 73, posts: 98, docs: 3, bioText: "Hi I'm a sophomore from Cyprus Bay and can help with most fields relating to high school math.", profileImage: UIImageView(), bgImage: UIImageView())

    func newThing(newName: String) {
        let newName = "Hi"
        print(newName)
        ProfileDatasource().user.username = newName
    }
}

2 个答案:

答案 0 :(得分:0)

这一行

it('issues the onChanged callback when the selected item is different', () => {
  const container = document.createElement('div');
  let dropdownRoot: HTMLElement | undefined;

  document.body.appendChild(container);

  const onChangedSpy = jasmine.createSpy('onChanged');

  try {
    ReactDOM.render(
      <Dropdown label="testgroup" defaultSelectedKey="1" onChanged={onChangedSpy} options={DEFAULT_OPTIONS} />,
      container
    );
    dropdownRoot = container.querySelector('.ms-Dropdown') as HTMLElement;

    ReactTestUtils.Simulate.click(dropdownRoot);

    const secondItemElement = document.querySelector('.ms-Dropdown-item[data-index="2"]') as HTMLElement;
    ReactTestUtils.Simulate.click(secondItemElement);
  } finally {
    expect(onChangedSpy).toHaveBeenCalledWith(DEFAULT_OPTIONS[2], 2);
  }
});

主要由此ProfileDatasource().user.username = newName 创建一个新的var,您需要

ProfileDatasource()

答案 1 :(得分:0)

在你试图改变username财产的行中,你是

  1. 创建一个全新的ProfileDatasource对象
  2. 从新user
  3. 获取ProfileDatasource媒体资源
  4. username设置为newName
  5. 之后,您的新ProfileDatasource被取消分配,并且没有任何真正的变化。如果要改变user属性,可以省略新对象的创建,如下所示:

    user.username = newName