首页 \ 问答 \ Swift:按键引用数组元素(Swift: reference to array element by key)

Swift:按键引用数组元素(Swift: reference to array element by key)

我编写了自己的小函数来使用键在数组中查找元素。 但我确信在Swift中有一个可以使用的实现来将它放在一行中。 任何提示?

func objectAtKey(array: [T], key: String) -> T? {
    for element in array {
        if element.name == key {
            return element
        }
    }
    return nil
}

我也知道函数indexOf,但这返回一个索引,我必须用于进一步的访问。 我认为这比较慢:

let index = array.indexOf({$0.name == key})

I have written my own small function to find an element in an array using a key. But I'm sure there is a ready to use implementation in Swift to get it in one line. Any hint?

func objectAtKey(array: [T], key: String) -> T? {
    for element in array {
        if element.name == key {
            return element
        }
    }
    return nil
}

I also know function indexOf, but this return an index, I have to use for further access. I think this is slower:

let index = array.indexOf({$0.name == key})

原文:https://stackoverflow.com/questions/39236301
更新时间:2022-09-06 09:09

最满意答案

优雅的解决方案是提供与比较器运算符的intersect (例如,在C ++中 )。
不幸的是,Matlab似乎并不支持这种功能/灵活性。

解决您的问题的方法是

% convert structs into matrices
A = [[a(:).x];[a(:).y]]';
B = [[b(:).x];[b(:).y]]';
% intersect the equivalent representation
[C, ia, ib] = intersect( A, B, 'rows' );
% map back to original structs
c = a(ia);

或者,您是否考虑使用从句柄类派生的类对象替换结构? 有可能重载类的关系运算符 ,然后应该可以直接对类对象进行排序(我没有仔细研究过这个解决方案 - 这只是我头脑中的一个提议)。


The elegant solution would have been to supply intersect with a comparator operator (like in , e.g., C++).
Unfortunaetly, Matlab does not seem to support this kind of functionality/flexibility.

A workaround for your problem would be

% convert structs into matrices
A = [[a(:).x];[a(:).y]]';
B = [[b(:).x];[b(:).y]]';
% intersect the equivalent representation
[C, ia, ib] = intersect( A, B, 'rows' );
% map back to original structs
c = a(ia);

Alternatively, have you considered replacing your structs with class objects derived from handle class? It might be possible to overload the relational operators of the class and then it should be possible to sort the class objects directly (I haven't looked closely into this solution - it's just a proposal off the tip of my head).

相关问答

更多
  • 使用repmat是预分配结构体的最有效方法: N = 10000; b = repmat(struct('x',1), N, 1 ); 这比使用Matlab 2011a要快10倍,而不是通过索引进行预分配 N = 10000; b(N).x = 1 索引方法只是稍微快于未预分配。 No preallocation: 0.075524 Preallocate Using indexing: 0.063774 Preallocate with repmat: ...
  • 优雅的解决方案是提供与比较器运算符的intersect (例如,在C ++中 )。 不幸的是,Matlab似乎并不支持这种功能/灵活性。 解决您的问题的方法是 % convert structs into matrices A = [[a(:).x];[a(:).y]]'; B = [[b(:).x];[b(:).y]]'; % intersect the equivalent representation [C, ia, ib] = intersect( A, B, 'rows' ); % map bac ...
  • 正如评论者提到的那样,并不能保证能够找到解决方案。 但是,您可以系统地确定解决方案是否存在,以及解决方案是否存在。 我将在大多数伪代码中描绘该方法: 用点和方向的归一化单位向量表示每条线是最容易的。 给定A线上的A1,A2和B线上的B1,B2,可以按如下方式进行: pA = A1, uA = (A2-A1)/norm(A2-A1). pB = B1, uB = (B2-B1)/norm(B2-B1). 注意, norm(uA) = 1 , norm(uB) = 1 。 然后沿着A线的点可以表示为: pA ...
  • 我会修改你的方法如下: 使用pdf 比率 ,而不是差异。 这样你就可以避免在交叉点之外检测到尾部。 最小化 ,而不是应用阈值。 Vectorize :一次计算所有点的比率(然后最小化)。 换一种说法: [~, index] = min(abs(Ray./Ric-1)); 在你的例子中,这给出了 >> index index = 2107 作为x索引的函数的pdf如下。 找到的intesection索引被认为是正确的(图中略高于2000): I would modify your approach ...
  • 什么错误信息相交给你? 这应该会给你一个提示,说明为什么它不起作用。 要完成你想要的任务,你不需要你的findPost函数(它有一个在postsFound=0;什么都不做的赋值postsFound=0;以及一个误导性命名的变量matchFound ,顺便说一句。),你可以使用逻辑索引。 iRed = strcmpi({InfoArray.FavouriteColor},'red'); iLondon = strcmpi({InfoArray.City},'London'); InfoArray(iRed & ...
  • 我认为以下代码可以帮助您 /* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throw ...
  • 根据Wolfie和烧杯的评论,下面是两个解决方案:一个使用最初提出的单元阵列样式,另一个使用数值数组而不是单元阵列(如果您只希望数字数据如你的例子)。 使用单元格数组: function [] = myFunction() % create a struct with the different vars W = struct('Band7', {7, 1099, 236, 260, 236, 260, 0},... 'Band2', {2, 1078, 236, 300, 236 ...
  • 我知道你想要的是交叉点,而不是两条曲线下面的区域。 如果这是准确的,那么使用匿名函数会更容易, mu1 = 0; mu2 = 1; sigma1 = sqrt(0.5); sigma2 = sqrt(0.5); dist1 =@(x) exp(-(x-mu1).^2 / (2*sigma1^2)) / sqrt(2*sigma1^2*pi); dist2 =@(x) exp(-(x-mu2).^2 / (2*sigma2^2)) / sqrt(2*sigma2^2*pi); fzero(@(x) dist1 ...
  • 这是一个使用unique和accumarray的矢量化方法,假设在输入单元阵列的每个单元格中没有重复 - [~,~,idx] = unique([tsCell_time{:}],'stable') out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time)) 样品运行 - >> tsCell_time = {[1 6 4 5],[4 7 1],[1 4 3],[4 3 1 7]}; >> InterSection = tsCell_time ...
  • 矢量化是避免循环和编写快速代码的主要工具。 将相同的操作应用于同类的许多元素时,可以使用它。 在这种情况下,您需要相同的操作,但元素是不同的。 使用循环(cellfun是)是唯一的可能性。 >> find(cellfun(@(x)(x.id),arr)==37) ans = 5 6 7 8 9 10 使用您描述的应用程序,我希望您将重复使用此行,至少要使用我建议使用函数的干净代码 >> cellfield=@(data,field)(cellfun(@( ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)