swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法

新建一个纯swift file文件

swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法_第1张图片


代码:

import Foundation

import UIKit

extension NSArray{

//检查index是否超过总大小

func stringAtCheckedIndex(index:NSInteger) -> (String){

if self.count <= index {

return ""

}else if index < 0 {

return ""

}else{

return self.object(at: index) as! (String)

}

}

//检查index是否超过总大小

func objectAtCheckedIndex(index:NSInteger) -> (AnyObject){

if self.count <= index {

return "" as (AnyObject)

}else if index < 0 {

return "" as (AnyObject)

}else{

return self.object(at: index) as (AnyObject)

}

}

}

extension NSDictionary{

//检查key是否存在

func objectForCheckedKey(key:AnyObject)-> (AnyObject){

let object = self.object(forKey: key)

if object == nil  {

return "" as (AnyObject)

}

return object as (AnyObject)

}

func stringForCheckedKey(key:String)-> (AnyObject){

let object = self.object(forKey: key)

if object is String  {

return object as (AnyObject)

}

if object is NSNumber{

return object as (AnyObject)

}

return "" as (AnyObject)

}

}

swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法_第2张图片
swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法_第3张图片

使用方法:

let a:NSMutableArray = ["1","3","4"];

let c = a.stringAtCheckedIndex(index: 2)

let b = a.stringAtCheckedIndex(index: 8)

let d:NSDictionary = ["三国演义":1,"水浒传":"施耐庵","红楼梦":"曹雪芹","西游记":"吴承恩"];

let e = d.stringForCheckedKey(key: "三国演义")

let r = d.stringForCheckedKey(key: ("123"))


这样,取下列为8,字典键123的值为空也不会崩溃。

swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法_第4张图片

你可能感兴趣的:(swift 3.1 避免数组越界,字典取不到值为空崩溃扩展方法)