ios - Swift 3.0 中的 Objective C 代码
<p><p>我一直在尝试将一段代码从 Objective C 转换为 Swift 3.0 语法,但没有成功。请在下面找到 objective-c代码。</p>
<p><strong> Objective-C </strong></p>
<pre><code> NSCharacterSet *invalidCharSet = [ invertedSet];
NSString *filtered = [ componentsJoinedByString:@""];
</code></pre>
<p>这是我尝试过的,</p>
<p><strong>Swift 3.0</strong></p>
<pre><code>let invalidCharSet : NSCharacterSet = NSCharacterSet.init(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").inverted as NSCharacterSet
let filtered = (replacementString.components(separatedBy: invalidCharSet)as NSArray).componentsJoined(by: "")
</code></pre>
<p>第二条语句(即filtered = ..)给出以下错误,</p>
<p><strong>错误</strong></p>
<blockquote>
<p>'components' produces '', not the expected contextual result
type 'NSArray'</p>
</blockquote></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>不要使用 NSArray,使用 Swift 数组并在其上调用 <code>.joined</code>。作为一般规则,在 Swift 中,尽量避免使用 Foundation,最好使用 Swift 自己的类型化工具。</p>
<pre><code>let invalidCharSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ").inverted
let filtered = replacementString.components(separatedBy: invalidCharSet).joined(separator: " ")
</code></pre></p>
<p style="font-size: 20px;">关于ios - Swift 3.0 中的 Objective C 代码,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39572924/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39572924/
</a>
</p>
页:
[1]