小编zek*_*kel的帖子

从文本文件中读取和写入字符串

我需要从文本文件中读取和写入数据,但我无法弄清楚如何.

我在Swift的iBook中找到了这个示例代码,但我仍然不知道如何编写或读取数据.

import Cocoa

class DataImporter
{
    /*
    DataImporter is a class to import data from an external file.
    The class is assumed to take a non-trivial amount of time to initialize.
    */
    var fileName = "data.txt"
    // the DataImporter class would provide data importing functionality here
}

class DataManager
{
    @lazy var importer = DataImporter()
    var data = String[]()
    // the DataManager class would provide data management functionality here
}

let manager = DataManager()
manager.data += "Some data"
manager.data …
Run Code Online (Sandbox Code Playgroud)

file-io swift

273
推荐指数
7
解决办法
38万
查看次数

如何将JSON字符串反序列化为NSDictionary?(适用于iOS 5+)

在我的iOS 5应用程序中,我有一个NSString包含JSON字符串的应用程序.我想将JSON字符串表示反序列化为本机NSDictionary对象.

 "{\"password\" : \"1234\",  \"user\" : \"andreas\"}"
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:@"{\"2\":\"3\"}"
                                options:NSJSONReadingMutableContainers
                                  error:&e];  
Run Code Online (Sandbox Code Playgroud)

但它会引发运行时错误.我究竟做错了什么?

-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c 
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFConstantString bytes]: unrecognized selector sent to instance 0x1372c'
Run Code Online (Sandbox Code Playgroud)

json nsdictionary nsstring ios ios5

151
推荐指数
4
解决办法
15万
查看次数

使用Swift 4中的JSONDecoder,缺少的键可以使用默认值而不必是可选属性吗?

Swift 4添加了新Codable协议.当我使用JSONDecoder它似乎要求我的Codable类的所有非可选属性在JSON中有键或它会引发错误.

使我的类的每个属性都是可选的似乎是一个不必要的麻烦,因为我真正想要的是使用json中的值或默认值.(我不希望这个属性为零.)

有没有办法做到这一点?

class MyCodable: Codable {
    var name: String = "Default Appleseed"
}

func load(input: String) {
    do {
        if let data = input.data(using: .utf8) {
            let result = try JSONDecoder().decode(MyCodable.self, from: data)
            print("name: \(result.name)")
        }
    } catch  {
        print("error: \(error)")
        // `Error message: "Key not found when expecting non-optional type
        // String for coding key \"name\""`
    }
}

let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) …
Run Code Online (Sandbox Code Playgroud)

json swift swift4 codable

88
推荐指数
5
解决办法
3万
查看次数

如何在三元条件运算符中使用Optional变量?

我想使用一个可选变量与三元条件运算符,但它抛出错误此错误:可选不能用作布尔值.我究竟做错了什么?

var str1: String?
var myBool:Bool
myBool = str1 ? true : false
Run Code Online (Sandbox Code Playgroud)

ternary-operator swift

56
推荐指数
4
解决办法
6万
查看次数

如何使用python正则表达式替换使用捕获的组?

假设我想the blue dog and blue cat wore blue hats改为the gray dog and gray cat wore blue hats.

随着sed我能做到这一点,如下所示:

$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
Run Code Online (Sandbox Code Playgroud)

如何在Python中进行类似的替换?我试过了:

>>> import re
>>> s = "the blue dog and blue cat wore blue hats"
>>> p = re.compile(r"blue (dog|cat)")
>>> p.sub('gray \1',s)
'the gray \x01 and gray \x01 wore blue hats'
Run Code Online (Sandbox Code Playgroud)

python regex replace sed

51
推荐指数
4
解决办法
4万
查看次数

你如何展示Xcode的构建日志?(尝试验证是否正确创建了iPhone分发构建zip.)

我正在尝试压缩我的iPhone应用程序以进行App Store分发.

分发说明建议查看构建日志以检查是否包含mobileprovision文件,但我无法弄清楚如何显示构建日志.

Apple的说明:

要确认您的构建成功,请检查以下内容:

打开Build Log详细信息视图并确认是否存在"embedded.mobileprovision"文件.这将带您进入构建日志中显示已成功调用供应配置文件的行.

iphone macos xcode objective-c

35
推荐指数
3
解决办法
4万
查看次数

在Swift中的视图控制器之间传递数据

我正在尝试将应用程序从Objective-C转换为Swift,但我找不到如何使用Swift在视图之间传递数据.我的Objective-C代码是

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
AnsViewController *ansViewController;
ansViewController = [storyBoard instantiateViewControllerWithIdentifier:@"ansView"];
ansViewController.num = theNum;
[self presentViewController:ansViewController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

它正在做的是它基本上取变量theNum,并将其传递给另一个视图控制器上的变量num.我知道这可能是一个简单的问题,但我对Swift非常困惑,所以如果有人能解释他们如何将其改为Swift,我将不胜感激!

谢谢

ios uistoryboard uistoryboardsegue swift

27
推荐指数
2
解决办法
5万
查看次数

在Swift中,获取数组中最后两项的最简洁方法是什么?

是否有更简洁的方法来获取Swift中数组的最后两项?一般来说,我试图避免这种方法,因为它很容易与索引一个接一个.(在本例中使用Swift 1.2.)

// Swift -- slices are kind of a hassle?
let oneArray = ["uno"]
let twoArray = ["uno", "dos"]
let threeArray = ["uno", "dos", "tres"]

func getLastTwo(array: [String]) -> [String] {
    if array.count <= 1 {
        return array
    } else {
        let slice: ArraySlice<String> = array[array.endIndex-2..<array.endIndex]
        var lastTwo: Array<String> = Array(slice)
        return lastTwo
    }
}

getLastTwo(oneArray)   // ["uno"]
getLastTwo(twoArray)   // ["uno", "dos"]
getLastTwo(threeArray) // ["dos", "tres"]
Run Code Online (Sandbox Code Playgroud)

我希望能有更接近Python的便利性.

## Python -- very convenient slices
myList = ["uno", "dos", "tres"]
print …
Run Code Online (Sandbox Code Playgroud)

arrays slice swift

25
推荐指数
4
解决办法
2万
查看次数

你可以从Swift应用程序执行Applescript脚本吗?

我有一个发送电子邮件的简单AppleScript.如何在Swift应用程序中调用它?

(我无法通过谷歌找到答案.)

applescript swift

24
推荐指数
3
解决办法
2万
查看次数

你能在Objective-C中添加自定义编译器警告吗?

(我在写这个问题时在其他地方找到了答案,但我认为如果我发布它可能对其他人有帮助,因为我在这里找不到任何东西.)

我想标记需要更好的错误处理的方法.我希望它们显示为编译器警告,以便其他开发人员(可能负责该区域)会注意到,并希望在他们的闲暇时解决.

(其他方法受欢迎,我看了, __attribute__((warning))但无法让它工作.)

compiler-construction xcode objective-c compiler-warnings

23
推荐指数
1
解决办法
1万
查看次数