最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【基本解决】Swift中如何实现NSNotFound

Swift crifan 4145浏览 0评论

【背景】

swift代码:

        var lastIndex:UInt = _selectedIndex
       
        self.selectedIndex = NSNotFound
        self.selectedIndex = lastIndex;

出错:

Cannot assign a value of type ‘Int’ to a value of type ‘UInt’

看起来是:

NSNotFound饰int类型,而此处lastIndex是Uint类型,所以报错。

但是此处更重要的是:

如何在swift实现NSNotFound

【解决过程】

1.搜:

swift NSNotFound

参考:

Working with NSNotFound in Swift – Tony Arnold

ios – Swift: Ambiguos reference to NSNotFound – Stack Overflow

How do I check if a string contains another string in Swift? – Stack Overflow

2.搜:

swift NSNotFound int

参考:

Working with NSNotFound in Swift – Tony Arnold

Foundation Constants Reference

NSNotFound

Defines a value that indicates that an item requested couldn’t be found or doesn’t exist.

Declaration

SWIFT

var NSNotFound: Int { get }

Constants
  • NSNotFound

    A value that indicates that an item requested couldn’t be found or doesn’t exist.

    Available in iOS 2.0 through iOS 8.4.

Discussion

NSNotFound is typically used by various methods and functions that search for items in serial data and return indices, such as characters in a string object or id objects in an NSArray object.

好像iOS 9就没了?

那我此处是iOS 9,就最好,也不能,再用了?

3.搜:

swift NSNotFound UInt

参考:

Working with NSNotFound in Swift – Tony Arnold

或许可以写成:

UInt(Foundation.NSNotFound)

结果:

selectedIndex = UInt(Foundation.NSNotFound)

真的可以通过编译。

 

【总结】

此处根据官网:

Foundation Constants Reference

的解释:

1.NSNotFound的用法:

主要用于检索:

字符串里的某个字符

数组里面某个元素

但是没有得到有效的(index类的)值

的时候,返回NSNotFound

 

2.iOS 9是否有效

根据官网的“Available in iOS 2.0 through iOS 8.4.”

-》感觉是:iOS 9就不存在此常量了。

-》但是根据Xcode中去看定义:

xcode foundation nsnotfound definition

好像又是:

没有限定iOS的版本啊。

-》

目前暂定的结论是:

iOS9中也还是可以使用NSNotFound的

 

然后需要注意,NSNotFound是Int类型

-》如果要和UInt类型混用,则要注意类型转换。

比如:

selectedIndex = UInt(Foundation.NSNotFound) 

这种。

转载请注明:在路上 » 【基本解决】Swift中如何实现NSNotFound

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.144 seconds, using 22.08MB memory