[英]Swift passing element as variable
In javascript I know i can something like the following: 在javascript中,我知道我可以执行以下操作:
var foo = '';
function changeVariable(variable, data){
this[variable] = data;
}
changeVariable("foo", "bar");
Is there away I can do this in swift? 我可以迅速离开那里吗?
func toggleFadeIn (element: String, active: Bool)
{
if(!active){
self.element.alpha = 0;
self.element.transform = CGAffineTransform(translationX: 0, y: 25)
}
}
Javascript is a dynamic language that has the facilities of modifying objects in such a way at runtime. Javascript是一种动态语言,具有在运行时以这种方式修改对象的功能。
Static languages (like Swift, Java, C#, and many others) require a reflection library to implement such behaviour. 静态语言(例如Swift,Java,C#和许多其他语言)需要反射库来实现这种行为。 Unfortunately, Swift has a really limited reflection capability (
Mirror
) and doesn't have the ability to modify object/struct members by their String
names, yet. 不幸的是,Swift的反射功能(
Mirror
)确实非常有限,并且还不能通过其String
名称来修改对象/结构成员。
If you elaborate on what exactly you were trying to achieve with this, we would be better able to suggest solutions. 如果您详细说明您要实现的目标,我们将能够更好地提出解决方案。
What you describe IS possible using KVO on NSObjects
. 您描述的内容可以在
NSObjects
上使用KVO来实现。 It relies on Objective-C dynamic messaging, but it does work. 它依赖于Objective-C动态消息传递,但是它确实起作用。 Take a look a the function
setValue:forKey:
, as documented in Apple's Key Value Programming Guide . 看一下Apple的《键值编程指南》中记录的
setValue:forKey:
函数。
Note that this is decidedly un-swiftlike, and not recommended. 请注意,这绝对不像雨燕一样,不建议这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.