Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Class 为什么当我试图在Swift中将代码放入类中时,对常量的引用消失了?_Class_Swift - Fatal编程技术网

Class 为什么当我试图在Swift中将代码放入类中时,对常量的引用消失了?

Class 为什么当我试图在Swift中将代码放入类中时,对常量的引用消失了?,class,swift,Class,Swift,我试图在Swift中使用NSTimer,但我遇到了问题,因为我在一个新的Swift文件中编写了代码,所以它不会从NSObject继承。我(勉强)理解NSTimer需要一个选择器,它需要这种继承。因此,我似乎应该在导入之后获取所有代码,并将整个内容包装在类定义中(现在我考虑到这一点,这也有其他优点)。但它不起作用。 例如: var recordSettings = [ AVFormatIDKey: kAudioFormatAppleLossless, AVEncoderAudioQualityKe

我试图在Swift中使用NSTimer,但我遇到了问题,因为我在一个新的Swift文件中编写了代码,所以它不会从NSObject继承。我(勉强)理解NSTimer需要一个选择器,它需要这种继承。因此,我似乎应该在导入之后获取所有代码,并将整个内容包装在类定义中(现在我考虑到这一点,这也有其他优点)。但它不起作用。 例如:

var recordSettings = [
AVFormatIDKey: kAudioFormatAppleLossless,
AVEncoderAudioQualityKey : AVAudioQuality.Max.toRaw(),
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100.0]
let nameFileUrl = NSURL(fileURLWithPath:"somePath")
let nameRecorder = AVAudioRecorder(URL: nameFileUrl, settings: recordSettings, error: &error)
那很好用。但是

class someClass: NSObject {
   var recordSettings = [
   AVFormatIDKey: kAudioFormatAppleLossless,
   AVEncoderAudioQualityKey : AVAudioQuality.Max.toRaw(),
   AVEncoderBitRateKey : 320000,
   AVNumberOfChannelsKey: 2,
   AVSampleRateKey : 44100.0]
   let nameFileUrl = NSURL(fileURLWithPath:"somePath")
   let nameRecorder = AVAudioRecorder(URL: nameFileUrl, settings: recordSettings, error: &error)
}

在“let namecorder”行上显示“someClass.Type没有名为“nameFileUrl”的成员”错误。当我试图调用这些变量或常量定义时,不会看到它们。我尝试了self.nameFileUrl和someClass.nameFileUrl,但似乎没有任何效果。我假设这与范围有关,但作为一个白痴,我学会了不相信自己的假设。 任何帮助都将不胜感激

class SomeClass: NSObject {
    var recordSettings = [
        AVFormatIDKey: kAudioFormatAppleLossless,
        AVEncoderAudioQualityKey : AVAudioQuality.Max.toRaw(),
        AVEncoderBitRateKey : 320000,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey : 44100.0]

    let nameFileUrl = NSURL(fileURLWithPath:"somePath")
    let nameRecorder : AVAudioRecorder?

    override init() {
        var error: NSError?
        nameRecorder = AVAudioRecorder(URL: nameFileUrl, settings: recordSettings, error: &error)
        if nameRecorder == nil {
            println("Error: \(error)")
        }
    }
}

var someClass : SomeClass = SomeClass()
// ... use someClass

必须在方法中定义nameRecorder。在这里,我在构造函数中实现了这一点(不一定是理想的),但您会明白这一点。

注意,您应该大写类型定义:
SomeClass
,而不是
SomeClass
。谢谢您的回答。当我首先将录音机声明为可选的“var namecorder:AVAudioRecorder?”时,它开始工作,然后在我用方法定义录音机之后,我需要“解包”可选的录音机,因此对录音机的所有调用都需要“!”类似的“namecorder!.prepareToRecord()”,感谢您让我走上了正确的道路!