repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
deltaDNA/ios-smartads-sdk | IntegrationTester/DetailViewController.swift | 1 | 3286 | //
// Copyright (c) 2017 deltaDNA Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var resultLabel: VerticalTopAlignLabel!
@IBOutlet weak var showedSwitch: UISwitch!
@IBOutlet weak var clickedSwitch: UISwitch!
@IBOutlet weak var leftApplicationSwitch: UISwitch!
@IBOutlet weak var closedSwitch: UISwitch!
@IBOutlet weak var adsShown: UILabel!
@IBOutlet weak var rewardedLabel: UILabel!
@IBAction func requestAd(_ sender: AnyObject) {
self.adNetwork?.requestAd()
}
@IBAction func showAd(_ sender: AnyObject) {
self.adNetwork?.showAd(viewController: self)
}
var adNetwork: AdNetwork! {
willSet (newAdNetwork) {
adNetwork?.delegate = nil
}
didSet {
adNetwork?.delegate = self
self.refreshUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshUI() {
if let adNetwork = adNetwork {
logoImageView?.image = adNetwork.logo()
versionLabel?.text = adNetwork.version()
nameLabel?.text = adNetwork.name
resultLabel?.text = adNetwork.adResult
showedSwitch?.isOn = adNetwork.showedAd
clickedSwitch?.isOn = adNetwork.clickedAd
leftApplicationSwitch?.isOn = adNetwork.leftApplication
closedSwitch?.isOn = adNetwork.closedAd
adsShown?.text = adNetwork.adCount > 0 ? String(format: "x\(adNetwork.adCount)") : ""
if adNetwork.closedAd {
rewardedLabel?.text = adNetwork.canReward ? "reward" : "no reward"
} else {
rewardedLabel?.text = ""
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension DetailViewController: AdNetworkSelectionDelegate {
func adNetworkSelected(newAdNetwork: AdNetwork) {
adNetwork = newAdNetwork
}
}
extension DetailViewController: AdNetworkDelegate {
func update() {
refreshUI()
}
}
| apache-2.0 | 3fd7ac0eb45a719f1d34188ac76f7104 | 30.902913 | 106 | 0.651856 | 4.701001 | false | false | false | false |
klundberg/swift-corelibs-foundation | Foundation/NSError.swift | 1 | 9249 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
public let NSCocoaErrorDomain: String = "NSCocoaErrorDomain"
public let NSPOSIXErrorDomain: String = "NSPOSIXErrorDomain"
public let NSOSStatusErrorDomain: String = "NSOSStatusErrorDomain"
public let NSMachErrorDomain: String = "NSMachErrorDomain"
public let NSUnderlyingErrorKey: String = "NSUnderlyingError"
public let NSLocalizedDescriptionKey: String = "NSLocalizedDescription"
public let NSLocalizedFailureReasonErrorKey: String = "NSLocalizedFailureReason"
public let NSLocalizedRecoverySuggestionErrorKey: String = "NSLocalizedRecoverySuggestion"
public let NSLocalizedRecoveryOptionsErrorKey: String = "NSLocalizedRecoveryOptions"
public let NSRecoveryAttempterErrorKey: String = "NSRecoveryAttempter"
public let NSHelpAnchorErrorKey: String = "NSHelpAnchor"
public let NSStringEncodingErrorKey: String = "NSStringEncodingErrorKey"
public let NSURLErrorKey: String = "NSURL"
public let NSFilePathErrorKey: String = "NSFilePathErrorKey"
public class NSError : NSObject, NSCopying, NSSecureCoding, NSCoding {
typealias CFType = CFError
internal var _cfObject: CFType {
return CFErrorCreate(kCFAllocatorSystemDefault, domain._cfObject, code, nil)
}
// ErrorType forbids this being internal
public var _domain: String
public var _code: Int
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
private var _userInfo: [String : Any]?
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public init(domain: String, code: Int, userInfo dict: [String : Any]?) {
_domain = domain
_code = code
_userInfo = dict
}
public required init?(coder aDecoder: NSCoder) {
if aDecoder.allowsKeyedCoding {
_code = aDecoder.decodeInteger(forKey: "NSCode")
_domain = aDecoder.decodeObjectOfClass(NSString.self, forKey: "NSDomain")!._swiftObject
if let info = aDecoder.decodeObjectOfClasses([NSSet.self, NSDictionary.self, NSArray.self, NSString.self, NSNumber.self, NSData.self, NSURL.self], forKey: "NSUserInfo") as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjects([]) {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
} else {
var codeValue: Int32 = 0
aDecoder.decodeValue(ofObjCType: "i", at: &codeValue)
_code = Int(codeValue)
_domain = (aDecoder.decodeObject() as? NSString)!._swiftObject
if let info = aDecoder.decodeObject() as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjects([]) {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
}
}
public static func supportsSecureCoding() -> Bool {
return true
}
public func encode(with aCoder: NSCoder) {
if aCoder.allowsKeyedCoding {
aCoder.encode(_domain.bridge(), forKey: "NSDomain")
aCoder.encode(Int32(_code), forKey: "NSCode")
aCoder.encode(_userInfo?.bridge(), forKey: "NSUserInfo")
} else {
var codeValue: Int32 = Int32(self._code)
aCoder.encodeValue(ofObjCType: "i", at: &codeValue)
aCoder.encode(self._domain.bridge())
aCoder.encode(self._userInfo?.bridge())
}
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
return self
}
public var domain: String {
return _domain
}
public var code: Int {
return _code
}
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public var userInfo: [String : Any] {
if let info = _userInfo {
return info
} else {
return Dictionary<String, Any>()
}
}
public var localizedDescription: String {
let desc = userInfo[NSLocalizedDescriptionKey] as? String
return desc ?? "The operation could not be completed"
}
public var localizedFailureReason: String? {
return userInfo[NSLocalizedFailureReasonErrorKey] as? String
}
public var localizedRecoverySuggestion: String? {
return userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
}
public var localizedRecoveryOptions: [String]? {
return userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String]
}
public var recoveryAttempter: AnyObject? {
return userInfo[NSRecoveryAttempterErrorKey] as? AnyObject
}
public var helpAnchor: String? {
return userInfo[NSHelpAnchorErrorKey] as? String
}
internal typealias NSErrorProvider = (error: NSError, key: String) -> AnyObject?
internal static var userInfoProviders = [String: NSErrorProvider]()
public class func setUserInfoValueProviderForDomain(_ errorDomain: String, provider: ((NSError, String) -> AnyObject?)?) {
NSError.userInfoProviders[errorDomain] = provider
}
public class func userInfoValueProviderForDomain(_ errorDomain: String) -> ((NSError, String) -> AnyObject?)? {
return NSError.userInfoProviders[errorDomain]
}
}
extension NSError : Swift.Error { }
extension NSError : _CFBridgable { }
extension CFError : _NSBridgable {
typealias NSType = NSError
internal var _nsObject: NSType {
let userInfo = CFErrorCopyUserInfo(self)._swiftObject
var newUserInfo: [String: Any] = [:]
for (key, value) in userInfo {
if let key = key as? NSString {
newUserInfo[key._swiftObject] = value
}
}
return NSError(domain: CFErrorGetDomain(self)._swiftObject, code: CFErrorGetCode(self), userInfo: newUserInfo)
}
}
public protocol _ObjectTypeBridgeableErrorType : Swift.Error {
init?(_bridgedNSError: NSError)
}
public protocol __BridgedNSError : RawRepresentable, Swift.Error {
static var __NSErrorDomain: String { get }
}
public func ==<T: __BridgedNSError where T.RawValue: SignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax()
}
public extension __BridgedNSError where RawValue: SignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int { return Int(rawValue.toIntMax()) }
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(IntMax(_bridgedNSError.code)))
}
public final var hashValue: Int { return _code }
}
public func ==<T: __BridgedNSError where T.RawValue: UnsignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax()
}
public extension __BridgedNSError where RawValue: UnsignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int {
return Int(bitPattern: UInt(rawValue.toUIntMax()))
}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code))))
}
public final var hashValue: Int { return _code }
}
public protocol _BridgedNSError : __BridgedNSError, Hashable {
// TODO: Was _NSErrorDomain, but that caused a module error.
static var __NSErrorDomain: String { get }
}
| apache-2.0 | ce19d1f40e444fb1e49595de072a159b | 36.597561 | 199 | 0.653692 | 4.90403 | false | false | false | false |
benlangmuir/swift | test/attr/attr_final.swift | 22 | 3478 | // RUN: %target-typecheck-verify-swift
class Super {
final var i: Int { get { return 5 } } // expected-note{{overridden declaration is here}}
final func foo() { } // expected-note{{overridden declaration is here}}
final subscript (i: Int) -> Int { // expected-note{{overridden declaration is here}}
get {
return i
}
}
}
class Sub : Super {
override var i: Int { get { return 5 } } // expected-error{{property overrides a 'final' property}}
override func foo() { } // expected-error{{instance method overrides a 'final' instance method}}
override subscript (i: Int) -> Int { // expected-error{{subscript overrides a 'final' subscript}}
get {
return i
}
}
final override init() {} // expected-error {{'final' modifier cannot be applied to this declaration}} {{3-9=}}
}
struct SomeStruct {
final var i: Int = 1 // expected-error {{only classes and class members may be marked with 'final'}}
final var j: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}}
final func f() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
enum SomeEnum {
final var i: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}}
final func f() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
protocol SomeProtocol {
final var i: Int { get } // expected-error {{only classes and class members may be marked with 'final'}}
final func protoFunc() // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeProtocol {
final var i: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
final func protoExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeStruct {
final func structExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeEnum {
final func enumExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension Super {
final func someClassMethod() {} // ok
}
final func global_function() {} // expected-error {{only classes and class members may be marked with 'final'}}
final var global_var: Int = 1 // expected-error {{only classes and class members may be marked with 'final'}}
final
class Super2 {
var i: Int { get { return 5 } } // expected-note{{overridden declaration is here}}
func foo() { } // expected-note{{overridden declaration is here}}
subscript (i: Int) -> Int { // expected-note{{overridden declaration is here}}
get {
return i
}
}
}
class Sub2 : Super2 { //// expected-error{{inheritance from a final class 'Super2'}}
override var i: Int { get { return 5 } } // expected-error{{property overrides a 'final' property}}
override func foo() { } // expected-error{{instance method overrides a 'final' instance method}}
override subscript (i: Int) -> Int { // expected-error{{subscript overrides a 'final' subscript}}
get {
return i
}
}
final override init() {} // expected-error {{'final' modifier cannot be applied to this declaration}} {{3-9=}}
}
struct Box<T> {
final class Super3 {}
}
class Sub3: Box<Int>.Super3 {} // expected-error{{inheritance from a final class 'Box.Super3'}}
| apache-2.0 | a2f75414a7665ce891d0958c3c840c7e | 38.522727 | 127 | 0.67165 | 3.934389 | false | false | false | false |
sadawi/ModelKit | ModelKit/Models/Model.swift | 1 | 23300 | //
// Model.swift
// APIKit
//
// Created by Sam Williams on 11/7/15.
// Copyright © 2015 Sam Williams. All rights reserved.
//
import Foundation
public typealias Identifier = String
open class ModelValueTransformerContext: ValueTransformerContext {
/**
An object that is responsible for keeping track of canonical instances
*/
public var registry:ModelRegistry? = MemoryRegistry()
}
public extension ValueTransformerContext {
static let defaultModelContext = ModelValueTransformerContext(name: "model")
}
open class Model: NSObject, NSCopying, Observable, Blankable {
/**
The class to instantiate, based on a dictionary value. For example, your dictionary might include a "type" string.
Whatever class you attempt to return must be cast to T.Type, which is inferred to be Self.
In other words, if you don't return a subclass, it's likely that you'll silently get an instance of
whatever class defines this method.
*/
open class func instanceClass<T>(for dictionaryValue: AttributeDictionary) -> T.Type? {
return self as? T.Type
}
private static var prototypes = TypeDictionary<Model>()
private static func prototype<T: Model>(for type: T.Type) -> T {
if let existing = prototypes[type] as? T {
return existing
} else {
let prototype = type.init()
prototypes[type] = prototype
return prototype
}
}
/**
Attempts to instantiate a new object from a dictionary representation of its attributes.
If a registry is set, will attempt to reuse the canonical instance for its identifier
- parameter dictionaryValue: The attributes
- parameter configure: A closure to configure a deserialized model, taking a Bool flag indicating whether it was newly instantiated (vs. reused from registry)
*/
open class func from(dictionaryValue:AttributeDictionary, in context: ValueTransformerContext = .defaultModelContext, configure:((Model,Bool) -> Void)?=nil) -> Self? {
var instance = (self.instanceClass(for: dictionaryValue) ?? self).init()
(instance as Model).readDictionaryValue(dictionaryValue, in: context)
var isNew = true
if let modelContext = context as? ModelValueTransformerContext, let registry = modelContext.registry {
// If we have a canonical object for this id, swap it in
if let canonical = registry.canonicalModel(for: instance) {
isNew = false
instance = canonical
(instance as Model).readDictionaryValue(dictionaryValue, in: modelContext)
} else {
isNew = true
registry.didInstantiate(instance)
}
}
configure?(instance, isNew)
return instance
}
public required override init() {
super.init()
self.buildFields()
self.afterInit()
}
open func afterInit() { }
open func afterCreate() { }
open func beforeSave() { }
open func afterDelete() {
self.identifier = nil
}
/**
Returns a unique instance of this class for an identifier. If a matching instance is already registered, returns that. Otherwise, returns a new instance.
*/
open class func with(identifier: Identifier, in context: ModelValueTransformerContext) -> Self {
let instance = self.init()
instance.identifier = identifier
if let registry = context.registry {
if let canonical = registry.canonicalModel(for: instance) {
return canonical
} else {
registry.didInstantiate(instance)
}
}
return instance
}
/**
Returns a canonical instance corresponding to this instance.
*/
open func canonicalInstance(in context: ModelValueTransformerContext) -> Self {
return context.registry?.canonicalModel(for: self) ?? self
}
/**
Creates a clone of this model. It won't exist in the registry.
*/
open func copy(with zone: NSZone?) -> Any {
return self.copy(fields: nil)
}
open func copy(fields: [FieldType]?) -> Any {
return type(of: self).from(dictionaryValue: self.dictionaryValue(fields: fields))!
}
/**
Which field should be treated as the identifier?
If all the models in your system have the same identifier field (e.g., "id"), you'll probably want to just put that in your
base model class.
*/
open var identifierField: FieldType? {
return nil
}
/**
Attempts to find the identifier as a String or Int, and cast it to an Identifier (aka String)
(because it's useful to have an identifier with known type!)
*/
open var identifier:Identifier? {
get {
let value = self.identifierField?.anyObjectValue
if let value = value as? Identifier {
return value
} else if let value = value as? Int {
return String(value)
} else {
return nil
}
}
set {
if let id = newValue {
if let stringField = self.identifierField as? Field<String> {
stringField.value = id
} else if let intField = self.identifierField as? Field<Int> {
intField.value = Int(id)
}
} else {
self.identifierField?.anyValue = nil
}
}
}
// TODO: permissions
open var editable:Bool = true
open var loadState: LoadState = .loaded
/**
Removes all data from this instance except its identifier, and sets the loadState to .incomplete.
*/
open func unload() {
for field in self.interface.fields where field.key != self.identifierField?.key {
field.anyValue = nil
}
self.loadState = .incomplete
}
open class var name:String {
get {
if let name = NSStringFromClass(self).components(separatedBy: ".").last {
return name
} else {
return "Unknown"
}
}
}
open func cascadeDelete(_ cascade: ((Model)->Void), seenModels: inout Set<Model>) {
self.visitAllFields(action: { field in
if let modelField = field as? ModelFieldType , modelField.cascadeDelete {
if let model = modelField.anyObjectValue as? Model {
cascade(model)
} else if let models = modelField.anyObjectValue as? [Model] {
for model in models {
cascade(model)
}
}
}
}, seenModels: &seenModels)
}
/**
Finds a field (possibly belonging to a child model) for a key path, specified as a list of strings.
*/
open func field(at path:FieldPath) -> FieldType? {
var path = path
guard let firstComponent = path.shift() else { return nil }
let interface = self.interface
if let firstField = interface[firstComponent] {
if path.length == 0 {
// No more components. Just return the field
return firstField
} else if let firstValue = firstField.anyValue as? Model {
// There are more components remaining, and we can keep traversing key paths
return firstValue.field(at: path)
}
}
return nil
}
/**
Finds a field (possibly belonging to a child model) for a key path, specified as a single string.
The string will be split using `componentsForKeyPath(_:)`.
*/
open func field(at path:String) -> FieldType? {
return field(at: self.fieldPath(path))
}
/**
Splits a field keypath into an array of field names to be traversed.
For example, "address.street" might be split into ["address", "street"]
To change the default behavior, you'll probably want to subclass.
*/
open func fieldPath(_ path:String) -> FieldPath {
return FieldPath(path, separator: ".")
}
open func fieldPath(for field: FieldType) -> FieldPath? {
if let key = field.key {
return [key]
} else {
return nil
}
}
public var interface = Interface()
/**
Which fields should we include in the dictionaryValue?
By default, includes all of them.
*/
open func defaultFieldsForDictionaryValue() -> [FieldType] {
return self.interface.fields
}
/**
Look at the instance's fields, do some introspection and processing.
*/
internal func buildFields() {
for (key, field) in self.staticFields.fieldsByKey {
if field.key == nil {
field.key = key
}
self.initializeField(field)
self.interface[key] = field
}
}
public static func <<(object: Model, field: FieldType) {
object.add(field: field)
}
public func add(field: FieldType) {
guard let key = field.key else { return }
self.initializeField(field)
self.interface[key] = field
}
open subscript (key: String) -> Any? {
get {
return self[FieldPath(key)]
}
set {
return self[FieldPath(key)] = newValue
}
}
open subscript (keyPath: FieldPath) -> Any? {
get {
guard let field = self.field(at: keyPath) else { return nil }
return field.anyValue
}
set {
guard let field = self.field(at: keyPath) else { return }
field.anyValue = newValue
}
}
lazy open var staticFields: Interface = {
return self.buildStaticFields()
}()
/**
Builds a mapping of keys to fields. Keys are either the field's `key` property (if specified) or the property name of the field.
This can be slow, since it uses reflection. If you find this to be a performance bottleneck, consider overriding the `staticFields` var
with an explicit mapping of keys to fields.
*/
private func buildStaticFields() -> Interface {
let result = Interface()
let mirror = Mirror(reflecting: self)
mirror.eachChild { child in
if let label = child.label, let value = child.value as? FieldType {
// If the field has its key defined, use that; otherwise fall back to the property name.
let key = value.key ?? label
result[key] = value
}
}
return result
}
/**
Performs any model-level field initialization your class may need, before any field values are set.
*/
open func initializeField(_ field:FieldType) {
field.owner = self
// Can't add observeration blocks that take values, since the FieldType protocol doesn't know about the value type
field.addObserver { [weak self] in
var seen = Set<Model>()
self?.fieldValueChanged(field, at: [], seen: &seen)
}
// If it's a model field, add a deep observer for changes on its value.
if let modelField = field as? ModelFieldType {
modelField.addModelObserver(self, updateImmediately: false) { [weak self] model, fieldPath, seen in
let field = field
self?.fieldValueChanged(field, at: fieldPath, seen: &seen)
}
}
}
open func fieldValueChanged(_ field: FieldType, at relativePath: FieldPath, seen: inout Set<Model>) {
// Avoid cycles
guard !seen.contains(self) else { return }
if let path = self.fieldPath(for: field) {
let fullPath = path.appending(path: relativePath)
seen.insert(self)
self.notifyObservers(path: fullPath, seen: &seen)
}
}
public func visitAllFields(recursive:Bool = true, action:((FieldType) -> Void)) {
var seenModels: Set<Model> = Set()
self.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
}
private func visitAllFields(recursive:Bool = true, action:((FieldType) -> Void), seenModels:inout Set<Model>) {
guard !seenModels.contains(self) else { return }
seenModels.insert(self)
for field in self.interface.fields {
action(field)
if recursive {
if let value = field.anyObjectValue as? Model {
value.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
} else if let values = field.anyObjectValue as? NSArray {
for value in values {
if let model = value as? Model {
model.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
}
}
}
}
}
}
public func visitAllFieldValues(recursive:Bool = true, action:((Any?) -> Void)) {
var seenModels: Set<Model> = Set()
self.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
}
private func visitAllFieldValues(recursive:Bool = true, action:((Any?) -> Void), seenModels:inout Set<Model>) {
guard !seenModels.contains(self) else { return }
seenModels.insert(self)
for field in self.interface.fields {
action(field.anyValue)
if recursive {
if let value = field.anyObjectValue as? Model {
value.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
} else if let value = field.anyValue, let values = value as? NSArray {
// I'm not sure why I can't cast to [Any]
// http://stackoverflow.com/questions/26226911/how-to-tell-if-a-variable-is-an-array
for value in values {
action(value)
if let modelValue = value as? Model {
modelValue.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
}
}
}
}
}
}
/**
Converts this object to its dictionary representation, optionally limited to a subset of its fields. By default, it will
export all fields in `defaultFieldsForDictionaryValue` (which itself defaults to all fields) that have been loaded.
- parameter fields: An array of field objects (belonging to this model) to be included in the dictionary value.
- parameter in: A value transformer context, used to obtain the correct value transformer for each field.
- parameter includeField: A closure determining whether a field should be included in the result. By default, it will be included iff its state is .Set (i.e., it has been explicitly set since it was loaded)
*/
open func dictionaryValue(fields:[FieldType]?=nil, in context: ValueTransformerContext = .defaultContext, includeField: ((FieldType) -> Bool)?=nil) -> AttributeDictionary {
var seenFields:[FieldType] = []
var includeField = includeField
if includeField == nil {
includeField = { (field:FieldType) -> Bool in field.loadState == LoadState.loaded }
}
return self.dictionaryValue(fields: fields, seenFields: &seenFields, in: context, includeField: includeField)
}
internal func dictionaryValue(fields:[FieldType]? = nil, seenFields: inout [FieldType], in context: ValueTransformerContext = .defaultContext, includeField: ((FieldType) -> Bool)? = nil) -> AttributeDictionary {
let fields = fields ?? self.defaultFieldsForDictionaryValue()
var result:AttributeDictionary = [:]
let include = fields
for field in self.interface.fields {
if include.contains(where: { $0 === field }) && includeField?(field) != false {
field.write(to: &result, seenFields: &seenFields, in: context)
}
}
return result
}
/**
Read field values from a dictionary representation. If a field's key is missing from the dictionary,
but the field is included in the fields to be imported, its value will be set to nil.
- parameter dictionaryValue: The dictionary representation of this model's new field values
- parameter fields: An array of field objects whose values are to be found in the dictionary
- parameter in: A value transformer context, used to obtain the correct value transformer for each field
*/
open func readDictionaryValue(_ dictionaryValue: AttributeDictionary, fields:[FieldType]?=nil, in context: ValueTransformerContext=ValueTransformerContext.defaultContext) {
let fields = (fields ?? self.defaultFieldsForDictionaryValue())
for field in self.interface.fields {
if fields.contains(where: { $0 === field }) {
field.read(from: dictionaryValue, in: context)
}
}
}
/**
Finds all values that are incompletely loaded (i.e., a model instantiated from just a foreign key)
*/
open func incompleteChildModels(recursive:Bool = false) -> [Model] {
var results:[Model] = []
self.visitAllFieldValues(recursive: recursive) { value in
if let model = value as? Model, model.loadState == .incomplete {
results.append(model)
}
}
return results
}
/**
All models related with foreignKey fields
*/
open func foreignKeyModels() -> [Model] {
var results:[Model] = []
self.visitAllFields { field in
if let modelField = field as? ModelFieldType , modelField.foreignKey == true {
if let value = modelField.anyObjectValue as? Model {
results.append(value)
} else if let values = modelField.anyObjectValue as? [Model] {
for value in values {
results.append(value)
}
}
}
}
return results
}
// MARK: Validation
/**
Adds a validation error message to a field identified by a key path.
- parameter keyPath: The path to the field (possibly belonging to a child model) that has an error.
- parameter message: A description of what's wrong.
*/
open func addError(at path:FieldPath, message:String) {
if let field = self.field(at: path) {
field.addValidationError(message)
}
}
/**
Test whether this model passes validation. All fields will have their validation states updated.
By default, related models are not themselves validated. Use the `requireValid()` method on those fields for deeper validation.
*/
open func validate() -> ValidationState {
self.resetValidationState()
var messages: [String] = []
self.visitAllFields(recursive: false) { field in
if case .invalid(let fieldMessages) = field.validate() {
messages.append(contentsOf: fieldMessages)
}
}
if messages.count == 0 {
return .valid
} else {
return .invalid(messages)
}
}
open func resetValidationState() {
self.visitAllFields { $0.resetValidationState() }
}
// MARK: - Merging
/**
Merges field values from another model.
Fields are matched by key, and compared using `updatedAt` timestamps; the newer value wins.
*/
public func merge(from model: Model) {
self.merge(from: model, include: self.interface.fields)
}
public func merge(from model: Model, exclude excludedFields: [FieldType]) {
self.merge(from: model) { field, otherField in
!excludedFields.contains { $0 === field }
}
}
public func merge(from model: Model, if condition: @escaping ((FieldType, FieldType)->Bool)) {
let fields = self.interface.fields
merge(from: model, include: fields, if: condition)
}
open func merge(from model: Model, include includedFields: [FieldType], if condition: ((FieldType, FieldType) -> Bool)? = nil) {
let otherFields = model.interface
for field in includedFields {
if let key = field.key, let otherField = otherFields[key] {
var shouldMerge = true
if let condition = condition {
shouldMerge = condition(field, otherField)
}
if shouldMerge {
field.merge(from: otherField)
}
}
}
}
// MARK: -
/**
A object to be used as a standard prototypical instance of this class, for the purpose of accessing fields, etc.
It is reused when possible.
*/
public class func prototype() -> Self {
return Model.prototype(for: self)
}
open var observations = ObservationRegistry<ModelObservation>()
// MARK: - Observations
@discardableResult public func addObserver(_ observer: AnyObject?=nil, for fieldPath: FieldPath?=nil, updateImmediately: Bool = false, action:@escaping ModelObservation.Action) -> ModelObservation {
let observation = ModelObservation(fieldPath: fieldPath, action: action)
self.observations.add(observation, for: observer)
return observation
}
@discardableResult public func addObserver(updateImmediately: Bool, action:@escaping ((Void) -> Void)) {
self.addObserver(updateImmediately: updateImmediately) { _, _, _ in
action()
}
}
public func notifyObservers(path: FieldPath, seen: inout Set<Model>) {
// Changing a value at a path implies a change of all child paths. Notify accordingly.
var path = path
path.isPrefix = true
self.observations.forEach { observation in
observation.perform(model: self, fieldPath: path, seen: &seen)
}
}
public func removeObserver(_ observer: AnyObject) {
self.observations.remove(for: observer)
}
public func removeAllObservers() {
self.observations.clear()
}
// MARK: - Blankable
public var isBlank: Bool {
for field in self.interface.fields {
let value = field.anyValue
if let blankable = value as? Blankable {
if !blankable.isBlank {
return false
}
} else if value != nil {
return false
}
}
return true
}
}
| mit | db11f89d43180e05b1758b003bb3174c | 35.347894 | 215 | 0.590369 | 4.890638 | false | false | false | false |
antoniocasero/DOFavoriteButton | DOFavoriteButton/DOFavoriteButton.swift | 2 | 15670 | //
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import UIKit
@IBDesignable
open class DOFavoriteButton: UIButton {
fileprivate var imageShape: CAShapeLayer!
@IBInspectable open var image: UIImage! {
didSet {
createLayers(image: image)
}
}
@IBInspectable open var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (isSelected) {
imageShape.fillColor = imageColorOn.cgColor
}
}
}
@IBInspectable open var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!isSelected) {
imageShape.fillColor = imageColorOff.cgColor
}
}
}
fileprivate var circleShape: CAShapeLayer!
fileprivate var circleMask: CAShapeLayer!
@IBInspectable open var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.cgColor
}
}
fileprivate var lines: [CAShapeLayer]!
@IBInspectable open var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for line in lines {
line.strokeColor = lineColor.cgColor
}
}
}
fileprivate let circleTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
fileprivate let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
fileprivate let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
fileprivate let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable open var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override open var isSelected : Bool {
didSet {
if (isSelected != oldValue) {
if isSelected {
imageShape.fillColor = imageColorOn.cgColor
} else {
deselect()
}
}
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
public override convenience init(frame: CGRect) {
self.init(frame: frame, image: UIImage())
}
public init(frame: CGRect, image: UIImage!) {
super.init(frame: frame)
self.image = image
createLayers(image: image)
addTargets()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
createLayers(image: UIImage())
addTargets()
}
fileprivate func createLayers(image: UIImage!) {
self.layer.sublayers = nil
let imageFrame = CGRect(x: frame.size.width / 2 - frame.size.width / 4, y: frame.size.height / 2 - frame.size.height / 4, width: frame.size.width / 2, height: frame.size.height / 2)
let imgCenterPoint = CGPoint(x: imageFrame.midX, y: imageFrame.midY)
let lineFrame = CGRect(x: imageFrame.origin.x - imageFrame.width / 4, y: imageFrame.origin.y - imageFrame.height / 4 , width: imageFrame.width * 1.5, height: imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalIn: imageFrame).cgPath
circleShape.fillColor = circleColor.cgColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArc(withCenter: imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleMask.path = maskPath.cgPath
//===============
// line layer
//===============
lines = []
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.cgColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGMutablePath()
path.move(to: CGPoint(x: lineFrame.midX, y: lineFrame.midY))
path.addLine(to: CGPoint(x: lineFrame.origin.x + lineFrame.width / 2, y: lineFrame.origin.y))
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).cgPath
imageShape.fillColor = imageColorOff.cgColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
imageShape.mask = CALayer()
imageShape.mask!.contents = image.cgImage
imageShape.mask!.bounds = imageFrame
imageShape.mask!.position = imgCenterPoint
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(caTransform3D: CATransform3DIdentity), // 0/10
NSValue(caTransform3D: CATransform3DIdentity), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(caTransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(caTransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(caTransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
fileprivate func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: #selector(DOFavoriteButton.touchDown(_:)), for: UIControlEvents.touchDown)
self.addTarget(self, action: #selector(DOFavoriteButton.touchUpInside(_:)), for: UIControlEvents.touchUpInside)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragExit(_:)), for: UIControlEvents.touchDragExit)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragEnter(_:)), for: UIControlEvents.touchDragEnter)
self.addTarget(self, action: #selector(DOFavoriteButton.touchCancel(_:)), for: UIControlEvents.touchCancel)
}
func touchDown(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchUpInside(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragExit(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchCancel(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
open func select() {
isSelected = true
imageShape.fillColor = imageColorOn.cgColor
CATransaction.begin()
circleShape.add(circleTransform, forKey: "transform")
circleMask.add(circleMaskTransform, forKey: "transform")
imageShape.add(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].add(lineStrokeStart, forKey: "strokeStart")
lines[i].add(lineStrokeEnd, forKey: "strokeEnd")
lines[i].add(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
open func deselect() {
isSelected = false
imageShape.fillColor = imageColorOff.cgColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
| mit | 449f1bbf50c52b53c47a85a183998d49 | 38.471033 | 190 | 0.532163 | 3.879673 | false | false | false | false |
shaps80/Peek | Pod/Classes/Controllers & Views/Inspectors/PreviewCell.swift | 1 | 1386 | //
// PreviewCell.swift
// Peek
//
// Created by Shaps Benkau on 24/02/2018.
//
import UIKit
internal final class PreviewCell: UITableViewCell {
internal let previewImageView: UIImageView
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
previewImageView = UIImageView()
previewImageView.contentMode = .scaleAspectFit
previewImageView.clipsToBounds = true
previewImageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
previewImageView.setContentHuggingPriority(.defaultLow, for: .horizontal)
previewImageView.setContentHuggingPriority(.required, for: .vertical)
previewImageView.setContentCompressionResistancePriority(.required, for: .vertical)
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
addSubview(previewImageView, constraints: [
equal(\.layoutMarginsGuide.leadingAnchor, \.leadingAnchor),
equal(\.layoutMarginsGuide.trailingAnchor, \.trailingAnchor),
equal(\.topAnchor, constant: -16),
equal(\.bottomAnchor, constant: 16)
])
clipsToBounds = true
contentView.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | e8f72b9a307c9cd6e5d0c22a75674fd4 | 32.804878 | 95 | 0.676046 | 5.823529 | false | false | false | false |
whong7/swift-knowledge | 思维导图/4-3:网易新闻/网易新闻/NetworkTools.swift | 1 | 841 | //
// NetworkTools.swift
// 网易新闻
//
// Created by 吴鸿 on 2017/3/4.
// Copyright © 2017年 吴鸿. All rights reserved.
//
import UIKit
import Alamofire
enum methodType {
case get
case post
}
class NetworkTools {
//类方法
class func requestData(URLString : String,type : methodType,parameters:[String : Any]? = nil,finishedCallback: @escaping(_ result : Any)->()){
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
//1.校验是否有结果
guard let result = response.result.value else{
return
}
//2.将结果回调出去
finishedCallback(result)
}
}
}
| mit | 70b0e41708e2c11c42b32ab3d9fe0941 | 20.297297 | 146 | 0.577411 | 4.169312 | false | false | false | false |
CD1212/Doughnut | Pods/GRDB.swift/GRDB/Core/SchedulingWatchdog.swift | 1 | 2605 | import Dispatch
/// SchedulingWatchdog makes sure that databases connections are used on correct
/// dispatch queues, and warns the user with a fatal error whenever she misuses
/// a database connection.
///
/// Generally speaking, each connection has its own dispatch queue. But it's not
/// enough: users need to use two database connections at the same time:
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
/// single dispatch queue can be temporarily shared by two or more connections.
///
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
/// dispatch queue that allows one database.
///
/// It does so by registering one instance of SchedulingWatchdog as a specific
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
///
/// Later on, the queue can be shared by several databases with the method
/// allowing(databases:execute:). See SerializedDatabase.sync() for
/// an example.
///
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
}
static func makeSerializedQueue(allowingDatabase database: Database) -> DispatchQueue {
let queue = DispatchQueue(label: "GRDB.SerializedDatabase")
let watchdog = SchedulingWatchdog(allowedDatabase: database)
queue.setSpecific(key: specificKey, value: watchdog)
return queue
}
// Temporarily allows `databases` while executing `body`
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
let backup = allowedDatabases
allowedDatabases.append(contentsOf: databases)
defer { allowedDatabases = backup }
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
}
static func allows(_ db: Database) -> Bool {
return current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
}
}
| gpl-3.0 | f358d744b57d3cc5e1a47a800b593ef3 | 41.016129 | 190 | 0.697121 | 4.668459 | false | false | false | false |
apple/swift | test/Interpreter/SDK/GLKit.swift | 69 | 3996 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// NOTE: Clang used to miscompile GLKit functions on i386. rdar://problem/19184403
// On i386, it seems to work optimized mode, but fails in non-optimized.
// rdar://problem/26392402
// UNSUPPORTED: CPU=i386
// REQUIRES: objc_interop
// GLKit is not available on watchOS.
// UNSUPPORTED: OS=watchos
import GLKit
func printV4(_ v: GLKVector4) {
print("<\(v.x) \(v.y) \(v.z) \(v.w)>")
}
let x = GLKVector4Make(1, 0, 0, 0)
let y = GLKVector4Make(0, 1, 0, 0)
let z = GLKVector4Make(0, 0, 1, 0)
printV4(x) // CHECK: <1.0 0.0 0.0 0.0>
printV4(y) // CHECK-NEXT: <0.0 1.0 0.0 0.0>
printV4(z) // CHECK-NEXT: <0.0 0.0 1.0 0.0>
print(GLKVector4DotProduct(x, y)) // CHECK-NEXT: 0.0
let z2 = GLKVector4CrossProduct(x, y)
print(GLKVector4AllEqualToVector4(z, z2)) // CHECK-NEXT: true
infix operator • : MultiplicationPrecedence
infix operator ⨉ : MultiplicationPrecedence
func •(x: GLKVector4, y: GLKVector4) -> Float {
return GLKVector4DotProduct(x, y)
}
func ⨉(x: GLKVector4, y: GLKVector4) -> GLKVector4 {
return GLKVector4CrossProduct(x, y)
}
func ==(x: GLKVector4, y: GLKVector4) -> Bool {
return GLKVector4AllEqualToVector4(x, y)
}
print(x • y) // CHECK-NEXT: 0.0
print(x ⨉ y == z) // CHECK-NEXT: true
func printM4(_ m: GLKMatrix4) {
print("⎡\(m.m00) \(m.m01) \(m.m02) \(m.m03)⎤")
print("⎢\(m.m10) \(m.m11) \(m.m12) \(m.m13)⎥")
print("⎢\(m.m20) \(m.m21) \(m.m22) \(m.m23)⎥")
print("⎣\(m.m30) \(m.m31) \(m.m32) \(m.m33)⎦")
}
let flipXY = GLKMatrix4Make(0, 1, 0, 0,
1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1)
// CHECK-NEXT: ⎡0.0 1.0 0.0 0.0⎤
// CHECK-NEXT: ⎢1.0 0.0 0.0 0.0⎥
// CHECK-NEXT: ⎢0.0 0.0 1.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(flipXY)
// FIXME: GLKMatrix4MakeWithArray takes mutable pointer arguments for no
// good reason. rdar://problem/19124355
var flipYZElements: [Float] = [1, 0, 0, 0,
0, 0, 1, 0,
0, 1, 0, 0,
0, 0, 0, 1]
let flipYZ = GLKMatrix4MakeWithArray(&flipYZElements)
// CHECK-NEXT: ⎡1.0 0.0 0.0 0.0⎤
// CHECK-NEXT: ⎢0.0 0.0 1.0 0.0⎥
// CHECK-NEXT: ⎢0.0 1.0 0.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(flipYZ)
let rotateXYZ = GLKMatrix4Multiply(flipYZ, flipXY)
// CHECK-NEXT: ⎡0.0 0.0 1.0 0.0⎤
// CHECK-NEXT: ⎢1.0 0.0 0.0 0.0⎥
// CHECK-NEXT: ⎢0.0 1.0 0.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(rotateXYZ)
let y3 = GLKMatrix4MultiplyVector4(flipXY, x)
print(y == y3) // CHECK-NEXT: true
let y4 = GLKMatrix4MultiplyVector4(flipYZ, z)
print(y == y4) // CHECK-NEXT: true
let z3 = GLKMatrix4MultiplyVector4(rotateXYZ, x)
print(z == z3) // CHECK-NEXT: true
func •(x: GLKMatrix4, y: GLKMatrix4) -> GLKMatrix4 {
return GLKMatrix4Multiply(x, y)
}
func •(x: GLKMatrix4, y: GLKVector4) -> GLKVector4 {
return GLKMatrix4MultiplyVector4(x, y)
}
print(y == flipXY • x) // CHECK-NEXT: true
print(x == flipXY • y) // CHECK-NEXT: true
print(z == flipXY • z) // CHECK-NEXT: true
print(x == flipYZ • x) // CHECK-NEXT: true
print(z == flipYZ • y) // CHECK-NEXT: true
print(y == flipYZ • z) // CHECK-NEXT: true
print(z == rotateXYZ • x) // CHECK-NEXT: true
print(x == rotateXYZ • y) // CHECK-NEXT: true
print(y == rotateXYZ • z) // CHECK-NEXT: true
print(z == flipYZ • flipXY • x) // CHECK-NEXT: true
print(x == flipYZ • flipXY • y) // CHECK-NEXT: true
print(y == flipYZ • flipXY • z) // CHECK-NEXT: true
let xxx = GLKVector3Make(1, 0, 0)
let yyy = GLKVector3Make(0, 1, 0)
let zzz = GLKVector3Make(0, 0, 1)
print(GLKVector3DotProduct(xxx, yyy)) // CHECK-NEXT: 0.0
print(GLKVector3AllEqualToVector3(GLKVector3CrossProduct(xxx, yyy), zzz)) // CHECK-NEXT: true
let xx = GLKVector2Make(1, 0)
let yy = GLKVector2Make(0, 1)
print(GLKVector2DotProduct(xx, yy)) // CHECK-NEXT: 0.0
| apache-2.0 | 49ed9924457b9e261880bb8c1b892b97 | 30.593496 | 93 | 0.617859 | 2.481481 | false | false | false | false |
libiao88/Moya | Demo/DemoTests/MoyaProviderSpec.swift | 5 | 22147 | import Quick
import Moya
import Nimble
import ReactiveCocoa
import RxSwift
import Alamofire
class MoyaProviderSpec: QuickSpec {
override func spec() {
describe("valid endpoints") {
describe("with stubbed responses") {
describe("a provider", {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns stubbed data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns equivalent Endpoint instances for the same target") {
let target: GitHub = .Zen
let endpoint1 = provider.endpoint(target)
let endpoint2 = provider.endpoint(target)
expect(endpoint1).to(equal(endpoint2))
}
it("returns a cancellable object when a request is made") {
let target: GitHub = .UserProfile("ashfurrow")
let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in }
expect(cancellable).toNot(beNil())
}
it("uses the Alamofire.Manager.sharedInstance by default") {
expect(provider.manager).to(beIdenticalTo(Alamofire.Manager.sharedInstance))
}
it("accepts a custom Alamofire.Manager") {
let manager = Manager()
let provider = MoyaProvider<GitHub>(manager: manager)
expect(provider.manager).to(beIdenticalTo(manager))
}
})
it("notifies at the beginning of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Began {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Ended {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
describe("a provider with lazy data", { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
})
it("delays execution when appropriate") {
let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2))
let startDate = NSDate()
var endDate: NSDate?
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
endDate = NSDate()
done()
}
return
}
expect{
return endDate?.timeIntervalSinceDate(startDate)
}.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) )
}
describe("a provider with a custom endpoint resolver") { () -> () in
var provider: MoyaProvider<GitHub>!
var executed = false
let newSampleResponse = "New Sample Response"
beforeEach {
executed = false
let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in
executed = true
return endpoint.urlRequest
}
provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("executes the endpoint resolver") {
let target: GitHub = .Zen
provider.request(target, completion: { (data, statusCode, response, error) in })
let sampleData = target.sampleData as NSData
expect(executed).to(beTruthy())
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
called = true
}
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).toNot(beNil())
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical signals for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
// The synchronous nature of stubbed responses makes this kind of tricky. We use the
// subscribeNext closure to get the provider into a state where the signal has been
// added to the inflightRequests dictionary. Then we ask for an identical request,
// which should return the same signal. We can't *test* those signals equivalency
// due to the use of RACSignal.defer, but we can check if the number of inflight
// requests went up or not.
let outerSignal = provider.request(target)
outerSignal.subscribeNext { (object) -> Void in
response = object as? MoyaResponse
expect(provider.inflightRequests.count).to(equal(1))
// Create a new signal and force subscription, so that the inflightRequests dictionary is accessed.
let innerSignal = provider.request(target)
innerSignal.subscribeNext { (object) -> Void in
// nop
}
expect(provider.inflightRequests.count).to(equal(1))
}
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a RxSwift provider", { () -> () in
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen) >- subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) >- subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) >- subscribeNext { (response) -> Void in
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical observables for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
let parallelCount = 10
let observables = Array(0..<parallelCount).map { _ in provider.request(target) }
var completions = Array(0..<parallelCount).map { _ in false }
let queue = dispatch_queue_create("testing", DISPATCH_QUEUE_CONCURRENT)
dispatch_apply(observables.count, queue, { idx in
let i = idx
observables[i] >- subscribeNext { _ -> Void in
if i == 5 { // We only need to check it once.
expect(provider.inflightRequests.count).to(equal(1))
}
completions[i] = true
}
})
func allTrue(cs: [Bool]) -> Bool {
return cs.reduce(true) { (a,b) -> Bool in a && b }
}
expect(allTrue(completions)).toEventually(beTrue())
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> {
override init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, manager: Manager = Alamofire.Manager.sharedInstance) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure, manager: manager)
}
override func request(token: T, completion: MoyaCompletion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(1))
}
it("cancels network request when subscription is cancelled") {
var called = false
let target: GitHub = .Zen
let disposable = provider.request(target).subscribeCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
}
describe("with stubbed errors") {
describe("a provider") { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect(errored).toEventually(beTruthy())
}
it("returns stubbed data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1)
}
it("returns stubbed error data when present") {
var errorMessage = ""
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if let object = object {
errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String
}
}
expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1)
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
it("returns correct data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
})
describe("a failing reactive provider") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns the HTTP status code as the error code") {
var code: Int?
provider.request(.Zen).subscribeError { (error) -> Void in
code = error.code
}
expect(code).toNot(beNil())
expect(code).to(equal(401))
}
}
}
}
}
}
| mit | 1691aee6daf71948447ccbd0f79febc0 | 48.10643 | 381 | 0.440511 | 7.273235 | false | false | false | false |
wilfreddekok/Antidote | Antidote/ProfileDetailsController.swift | 1 | 7979 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import LocalAuthentication
protocol ProfileDetailsControllerDelegate: class {
func profileDetailsControllerSetPin(controller: ProfileDetailsController)
func profileDetailsControllerChangeLockTimeout(controller: ProfileDetailsController)
func profileDetailsControllerChangePassword(controller: ProfileDetailsController)
func profileDetailsControllerDeleteProfile(controller: ProfileDetailsController)
}
class ProfileDetailsController: StaticTableController {
weak var delegate: ProfileDetailsControllerDelegate?
private weak var toxManager: OCTManager!
private let pinEnabledModel = StaticTableSwitchCellModel()
private let lockTimeoutModel = StaticTableInfoCellModel()
private let touchIdEnabledModel = StaticTableSwitchCellModel()
private let changePasswordModel = StaticTableButtonCellModel()
private let exportProfileModel = StaticTableButtonCellModel()
private let deleteProfileModel = StaticTableButtonCellModel()
private var documentInteractionController: UIDocumentInteractionController?
init(theme: Theme, toxManager: OCTManager) {
self.toxManager = toxManager
var model = [[StaticTableBaseCellModel]]()
var footers = [String?]()
model.append([pinEnabledModel, lockTimeoutModel])
footers.append(String(localized: "pin_description"))
if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
model.append([touchIdEnabledModel])
footers.append(String(localized: "pin_touch_id_description"))
}
model.append([changePasswordModel])
footers.append(nil)
model.append([exportProfileModel, deleteProfileModel])
footers.append(nil)
super.init(theme: theme, style: .Grouped, model: model, footers: footers)
updateModel()
title = String(localized: "profile_details")
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateModel()
reloadTableView()
}
}
extension ProfileDetailsController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController) -> UIView? {
return view
}
func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController) -> CGRect {
return view.frame
}
}
private extension ProfileDetailsController {
func updateModel() {
let settings = toxManager.objects.getProfileSettings()
let isPinEnabled = settings.unlockPinCode != nil
pinEnabledModel.title = String(localized: "pin_enabled")
pinEnabledModel.on = isPinEnabled
pinEnabledModel.valueChangedHandler = pinEnabledValueChanged
lockTimeoutModel.title = String(localized: "pin_lock_timeout")
lockTimeoutModel.showArrow = true
lockTimeoutModel.didSelectHandler = changeLockTimeout
switch settings.lockTimeout {
case .Immediately:
lockTimeoutModel.value = String(localized: "pin_lock_immediately")
case .Seconds30:
lockTimeoutModel.value = String(localized: "pin_lock_30_seconds")
case .Minute1:
lockTimeoutModel.value = String(localized: "pin_lock_1_minute")
case .Minute2:
lockTimeoutModel.value = String(localized: "pin_lock_2_minutes")
case .Minute5:
lockTimeoutModel.value = String(localized: "pin_lock_5_minutes")
}
touchIdEnabledModel.enabled = isPinEnabled
touchIdEnabledModel.title = String(localized: "pin_touch_id_enabled")
touchIdEnabledModel.on = settings.useTouchID
touchIdEnabledModel.valueChangedHandler = touchIdEnabledValueChanged
changePasswordModel.title = String(localized: "change_password")
changePasswordModel.didSelectHandler = changePassword
exportProfileModel.title = String(localized: "export_profile")
exportProfileModel.didSelectHandler = exportProfile
deleteProfileModel.title = String(localized: "delete_profile")
deleteProfileModel.didSelectHandler = deleteProfile
}
func pinEnabledValueChanged(on: Bool) {
if on {
delegate?.profileDetailsControllerSetPin(self)
}
else {
let settings = toxManager.objects.getProfileSettings()
settings.unlockPinCode = nil
toxManager.objects.saveProfileSettings(settings)
}
updateModel()
reloadTableView()
}
func changeLockTimeout(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangeLockTimeout(self)
}
func touchIdEnabledValueChanged(on: Bool) {
let settings = toxManager.objects.getProfileSettings()
settings.useTouchID = on
toxManager.objects.saveProfileSettings(settings)
}
func changePassword(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangePassword(self)
}
func exportProfile(_: StaticTableBaseCell) {
do {
let path = try toxManager.exportToxSaveFile()
let name = UserDefaultsManager().lastActiveProfile ?? "profile"
documentInteractionController = UIDocumentInteractionController(URL: NSURL.fileURLWithPath(path))
documentInteractionController!.delegate = self
documentInteractionController!.name = "\(name).tox"
documentInteractionController!.presentOptionsMenuFromRect(view.frame, inView:view, animated: true)
}
catch let error as NSError {
handleErrorWithType(.ExportProfile, error: error)
}
}
func deleteProfile(cell: StaticTableBaseCell) {
let title1 = String(localized: "delete_profile_confirmation_title_1")
let title2 = String(localized: "delete_profile_confirmation_title_2")
let message = String(localized: "delete_profile_confirmation_message")
let yes = String(localized: "alert_delete")
let cancel = String(localized: "alert_cancel")
let alert1 = UIAlertController(title: title1, message: message, preferredStyle: .ActionSheet)
alert1.popoverPresentationController?.sourceView = cell
alert1.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert1.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
let alert2 = UIAlertController(title: title2, message: nil, preferredStyle: .ActionSheet)
alert2.popoverPresentationController?.sourceView = cell
alert2.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert2.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
self.reallyDeleteProfile()
})
alert2.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
})
alert1.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
presentViewController(alert1, animated: true, completion: nil)
}
func reallyDeleteProfile() {
delegate?.profileDetailsControllerDeleteProfile(self)
}
}
| mpl-2.0 | 937c571bba5ddde6a9681764fcf21802 | 38.895 | 155 | 0.702218 | 5.056401 | false | false | false | false |
glimpseio/ChannelZ | Playgrounds/ChannelZMac.playground/section-1.swift | 1 | 7896 | import Foundation
import ChannelZ
struct Song {
var title: String
}
struct Company {
var name: String
}
struct Artist {
var name: String
var label: Company?
var songs: [Song]
}
struct Album {
var title: String
var year: Int
var producer: Company?
var tracks: [Song]
}
struct Library {
var artists: [Artist] = []
var albums: [Album] = []
}
extension Library {
var songs: [Song] { return artists.flatMap({ $0.songs }) + albums.flatMap({ $0.tracks }) }
}
var library: Library = Library()
library.albums.append(Album(title: "Magenta Snow", year: 1983, producer: nil, tracks: [
Song(title: "Let's Get Silly"),
Song(title: "Take Me with You"),
Song(title: "I Would Die For You")
]))
// Make it funky now
library.albums[0].title = "Purple Rain"
//library.albums[0].tracks[0].title = "Let's Go Crazy"
//library.albums[0].tracks[1].title = "Take Me with U"
//library.albums[0].tracks[2].title = "I Would Die 4 U"
library.albums[0].year = 1984
library.albums[0].producer = Company(name: "Warner Brothers") // not so funky
library.artists.append(Artist(name: "Prince", label: nil, songs: [Song(title: "Red Hat")]))
library.artists[0].songs[0].title = "Raspberry Beret"
func funkify(title: String) -> String {
return title
.stringByReplacingOccurrencesOfString("Get Silly", withString: "Go Crazy")
.stringByReplacingOccurrencesOfString("For", withString: "4")
.stringByReplacingOccurrencesOfString("You", withString: "U")
}
for i in 0..<library.albums[0].tracks.count {
library.albums[0].tracks[i].title = funkify(library.albums[0].tracks[i].title)
}
//dump(library)
let titles = Set(library.songs.map({ $0.title }))
// Verify funkiness
let funky = titles == ["Let's Go Crazy", "Take Me with U", "I Would Die 4 U", "Raspberry Beret"]
// Make it funcy now ¯\_(ツ)_/¯
protocol Focusable {
}
extension Focusable {
static func lens<B>(lens: Lens<Self, B>) -> Lens<Self, B> {
return lens
}
static func lensZ<X, Source : StateEmitterType where Source.Element == Self>(lens: Lens<Self, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
return { channel in focus(channel)(lens) }
}
static func focus<X, Source : StateEmitterType where Source.Element == Self>(channel: Channel<Source, Mutation<Source.Element>>) -> (Lens<Source.Element, X>) -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
return channel.focus
}
}
extension Artist : Focusable {
static let nameλ = Artist.lens(Lens({ $0.name }, { $0.name = $1 }))
static let labelλ = Artist.lens(Lens({ $0.label }, { $0.label = $1 }))
static let songsλ = Artist.lens(Lens({ $0.songs }, { $0.songs = $1 }))
}
extension Company : Focusable {
static let nameλ = Company.lens(Lens({ $0.name }, { $0.name = $1 }))
}
//public extension ChannelType where Element : MutationType {
public extension ChannelType where Source : StateEmitterType, Element == Mutation<Source.Element> {
}
//extension ChannelType where Element : MutationType, Element.T : Focusable {
// func focus<B>(lens: Lens<Element.T, B>) {
// focus
// }
//}
let artist = transceive(library.artists[0])
artist.focus(Artist.nameλ).value = "Foo"
//artist.focus(Artist.labelλ).focus(<#T##lens: Lens<Company?, X>##Lens<Company?, X>#>)
//struct ArtistLens<B> {
// let lens: Lens<Artist, B>
// // error: static stored properties not yet supported in generic types
// static let name = ArtistLens(lens: Lens({ $0.name }, { $0.name = $1 }))
//}
1
//struct ArtistLenses<T> {
// static let name = Lens<Artist, String>({ $0.name }, { $0.name = $1 })
//}
//protocol Focusable {
// associatedtype Prism : PrismType
//}
//
//protocol PrismType {
// associatedtype Focus
//}
//
//extension Focusable {
// static func lensZ<X, Source : StateEmitterType where Source.Element == Self>(lens: Lens<Self, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return { channel in focus(channel)(lens) }
// }
//
// static func focus<X, Source : StateEmitterType where Source.Element == Self>(channel: Channel<Source, Mutation<Source.Element>>) -> (Lens<Source.Element, X>) -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return channel.focus
// }
//}
//
////public extension ChannelType where Source : StateEmitterType, Element == Mutation<Source.Element> {
//
//extension PrismType {
// static func lensZ<X, Source : StateEmitterType where Source.Element == Focus>(lens: Lens<Focus, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return { channel in channel.focus(lens) }
// }
//}
//
//extension Song : Focusable {
// var prop: () -> Channel<ValueTransceiver<Song>, Mutation<Song>> { return { transceive(self) } }
//
// struct Prism : PrismType {
// typealias Focus = Song
//// static let title = Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))
// }
//}
//
//protocol Prasm {
// associatedtype Focus
//// var channel: Channel<T, Mutation<T>> { get }
//}
//
//class BasePrasm<T, B> : Prasm {
// typealias Focus = T
// let lens: Lens<T, B>
//
// init(lens: Lens<T, B>) {
// self.lens = lens
// }
//}
//
//extension Artist : Focusable {
// static let nameZ = Lens<Artist, String>({ $0.name }, { $0.name = $1 })
// static let songsZ = Lens<Artist, [Song]>({ $0.songs }, { $0.songs = $1 })
//
// static func focal(prism: Prosm) {
//
// }
//
//// static let nameZ = Artist.lensZ(Lens({ $0.name }, { $0.name = $1 }))(transceive(Artist(name: "", songs: [])))
//
// struct Prism : PrismType {
// typealias Focus = Artist
//
// static let name = Prism(lens: Lens({ $0.name }, { $0.name = $1 }))
//// static let songs = Prism(lens: Lens({ $0.songs }, { $0.songs = $1 }))
//
// let lens: Lens<Artist, String>
// init(lens: Lens<Artist, String>) {
// self.lens = lens
// }
// }
//
// class Prosm<B> : BasePrasm<Artist, B> {
//// let nameZ = Prosm.lensZ(Lens({ $0.name }, { $0.name = $1 }))
// static let name = Prosm(lens: Lens({ $0.name }, { $0.name = $1 }))
//
// override init(lens: Lens<Artist, String>) {
// super.init(lens: lens)
// }
//
// }
//}
//
//
//extension Album : Focusable {
// struct Prism : PrismType {
// typealias Focus = Album
//// static let title = Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))
//// static let year = Prism.lensZ(Lens({ $0.year }, { $0.year = $1 }))
//// static let label = Prism.lensZ(Lens({ $0.label }, { $0.label = $1 }))
//// static let tracks = Prism.lensZ(Lens({ $0.tracks }, { $0.tracks = $1 }))
// }
//}
//
//// Prism=Λ, Lens=λ
//var prince = library.artists[0]
//
//let artistZ = transceive(prince)
//artistZ.value.name
//
//
//Artist.focal(.name)
//
//1
//
//
//let name = Artist.focus(artistZ)(Artist.Prism.name)
//let name = Artist.Prism.name(artistZ)
//
//let name = Artist.Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))(artistZ)
//name.value = "The Artist Formerly Known As Prince"
//artistZ.value.name
//let princeΛ = prince.focus()
//
//princeΛ.nameλ.get(prince)
//princeΛ.nameλ.value = "The Artist Formerly Known as Prince"
//princeΛ.nameλ.value
//princeName.value
//princeName ∞= "The Artist Formerly Known as Prince"
//princeName.value
//prism.title.get(song)
//
//song = prism.title.set(song, "Blueberry Tophat")
//
//prism.title.get(song)
//song.title
//let prop = transceive((int: 1, dbl: 2.2, str: "Foo", sub: (a: true, b: 22, c: "")))
| mit | 1e9bd99bb4681a20f54086461cd5b655 | 28.166667 | 247 | 0.61854 | 3.099174 | false | false | false | false |
tomburns/ios | FiveCalls/FiveCalls/MyImpactViewController.swift | 1 | 4409 | //
// MyImpactViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/6/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Crashlytics
import Rswift
class MyImpactViewController : UITableViewController {
var viewModel: ImpactViewModel!
var totalCalls: Int?
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var subheadLabel: UILabel!
enum Sections: Int {
case stats
case contacts
case count
var cellIdentifier: Rswift.ReuseIdentifier<UIKit.UITableViewCell>? {
switch self {
case .stats: return R.reuseIdentifier.statCell
case .contacts: return R.reuseIdentifier.contactStatCell
default: return nil
}
}
}
enum StatRow: Int {
case madeContact
case voicemail
case unavailable
case count
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
Answers.logCustomEvent(withName:"Screen: My Impact")
viewModel = ImpactViewModel(logs: ContactLogs.load().all)
let numberOfCalls = viewModel.numberOfCalls
headerLabel.text = impactMessage(for: numberOfCalls)
subheadLabel.isHidden = numberOfCalls == 0
let op = FetchStatsOperation()
op.completionBlock = {
self.totalCalls = op.numberOfCalls
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
OperationQueue.main.addOperation(op)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count.rawValue
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Sections(rawValue: section)! {
case .stats:
return StatRow.count.rawValue
case .contacts:
return 0
default: return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = Sections(rawValue: indexPath.section)!
let identifier = section.cellIdentifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath)!
switch section {
case .stats:
configureStatRow(cell: cell, stat: StatRow(rawValue: indexPath.row)!)
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let total = totalCalls, section == Sections.stats.rawValue else { return nil }
let statsVm = StatsViewModel(numberOfCalls: total)
return R.string.localizable.communityCalls(statsVm.formattedNumberOfCalls)
}
private func impactMessage(for numberOfCalls: Int) -> String {
switch numberOfCalls {
case 0:
return R.string.localizable.yourImpactZero(numberOfCalls)
case 1:
return R.string.localizable.yourImpactSingle(numberOfCalls)
default:
return R.string.localizable.yourImpactMultiple(numberOfCalls)
}
}
private func configureStatRow(cell: UITableViewCell, stat: StatRow) {
switch stat {
case .madeContact:
cell.textLabel?.text = R.string.localizable.madeContact()
cell.detailTextLabel?.text = timesString(count: viewModel.madeContactCount)
case .unavailable:
cell.textLabel?.text = R.string.localizable.unavailable()
cell.detailTextLabel?.text = timesString(count: viewModel.unavailableCount)
case .voicemail:
cell.textLabel?.text = R.string.localizable.leftVoicemail()
cell.detailTextLabel?.text = timesString(count: viewModel.voicemailCount)
default: break
}
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
private func timesString(count: Int) -> String {
guard count != 1 else { return R.string.localizable.calledSingle(count) }
return R.string.localizable.calledMultiple(count)
}
}
| mit | 5de4adc38781dfefda17282ff7f77126 | 31.175182 | 109 | 0.627042 | 5.155556 | false | false | false | false |
allbto/WayThere | ios/WayThere/Pods/Nimble/Nimble/Wrappers/MatcherFunc.swift | 158 | 2065 | import Foundation
public struct FullMatcherFunc<T>: Matcher {
public let matcher: (Expression<T>, FailureMessage, Bool) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage, Bool) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage, false)
}
public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return !matcher(actualExpression, failureMessage, true)
}
}
public struct MatcherFunc<T>: BasicMatcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage)
}
}
public struct NonNilMatcherFunc<T>: NonNilBasicMatcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage)
}
}
public func fullMatcherFromBasicMatcher<M: BasicMatcher>(matcher: M) -> FullMatcherFunc<M.ValueType> {
return FullMatcherFunc { actualExpression, failureMessage, expectingToNotMatch in
return matcher.matches(actualExpression, failureMessage: failureMessage) != expectingToNotMatch
}
}
public func basicMatcherWithFailureMessage<M: NonNilBasicMatcher>(matcher: M, postprocessor: (FailureMessage) -> Void) -> NonNilMatcherFunc<M.ValueType> {
return NonNilMatcherFunc<M.ValueType> { actualExpression, failureMessage in
let result = matcher.matches(actualExpression, failureMessage: failureMessage)
postprocessor(failureMessage)
return result
}
}
| mit | a345172678ed921ebee775ac63b61d4c | 36.545455 | 154 | 0.723487 | 4.952038 | false | false | false | false |
cc001/learnSwiftBySmallProjects | 18-LimitCharacters/LimitCharacters/ViewController.swift | 1 | 3807 | //
// ViewController.swift
// LimitCharacters
//
// Created by 陈闯 on 2016/12/25.
// Copyright © 2016年 陈闯. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var characterCountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
avatarImageView.layer.cornerRadius = 23
avatarImageView.clipsToBounds = true
tweetTextView.delegate = self
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
characterCountLabel.text = "\(140 - (textView.text?.characters.count)!)"
print(range.length, textView.text.characters.count)
// if range.length > 14 {
// return false
// } else {
let newLength = textView.text.characters.count + range.length
return newLength < 140
// }
}
func textViewDidChange(_ textView: UITextView) {
// var str = textView.text
// let endIndex: String.Index = advance(0, 10)
// var subStr = str.su
// textView.text = textView.text.substring(to: textView.text.sto.advancedBy(14))
}
func keyBoardWillShow(_ note:Notification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltaY = keyBoardBounds.size.height
let animations:(() -> Void) = {
self.bottomView.transform = CGAffineTransform(translationX: 0,y: -deltaY)
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else {
animations()
}
}
func keyBoardWillHide(_ note:Notification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomView.transform = CGAffineTransform.identity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | e8810f782753c0b41cdaa2fe36addfc0 | 31.444444 | 167 | 0.617229 | 5.415121 | false | false | false | false |
roambotics/swift | test/stdlib/StringSwitch.swift | 2 | 1835 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var StringSwitchTests = TestSuite("StringSwitchTests")
func switchOver(_ s: String) -> Character {
let (first, second) = ("first", "second")
let ret1: Character
switch s {
case first: ret1 = "A"
case second[...]: ret1 = "B"
default: ret1 = "X"
}
let ret2: Character
switch s[...] {
case first: ret2 = "A"
case second[...]: ret2 = "B"
default: ret2 = "X"
}
expectEqual(ret1, ret2)
return ret1
}
func switchOver<S1: StringProtocol, S2: StringProtocol>(
_ s1: S1, _ s2: S2
) -> Character {
let (first, second) = ("first", "second")
// FIXME: Enable (https://github.com/apple/swift/issues/54896)
#if true
fatalError()
#else
let ret1: Character
switch s1 {
case first: ret1 = "A"
case second[...]: ret1 = "B"
case s2: ret2 = "="
default: ret1 = "X"
}
let ret2: Character
switch s2 {
case first: ret1 = "A"
case second[...]: ret1 = "B"
case s1: ret2 = "="
default: ret2 = "X"
}
expectEqual(ret1, ret2)
return ret1
#endif
}
StringSwitchTests.test("switch") {
let (first, second) = ("first", "second")
let same = "same"
let (foo, bar) = ("foo", "bar")
expectEqual("A", switchOver(first))
expectEqual("B", switchOver(second))
expectEqual("X", switchOver(foo))
// FIXME: Enable (https://github.com/apple/swift/issues/54896)
#if true
#else
expectEqual("A", switchOver(first, first))
expectEqual("B", switchOver(second, second))
expectEqual("=", switchOver(same, same))
expectEqual("X", switchOver(foo, bar))
expectEqual("A", switchOver(first[...], first))
expectEqual("B", switchOver(second[...], second))
expectEqual("=", switchOver(same[...], same))
expectEqual("X", switchOver(foo[...], bar))
#endif
}
runAllTests()
| apache-2.0 | 590cf46694346fa9a29919fbcc9bfcc2 | 21.108434 | 64 | 0.619619 | 3.21366 | false | true | false | false |
xedin/swift | test/stdlib/VarArgs.swift | 10 | 4712 | // RUN: %target-run-stdlib-swift -parse-stdlib %s | %FileCheck %s
// REQUIRES: executable_test
import Swift
#if _runtime(_ObjC)
import Darwin
import CoreGraphics
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
typealias CGFloat = Double
#elseif os(Windows)
import MSVCRT
#if arch(x86_64) || arch(arm64)
typealias CGFloat = Double
#else
typealias CGFloat = Float
#endif
#else
#error("Unsupported platform")
#endif
func my_printf(_ format: String, _ arguments: CVarArg...) {
_ = withVaList(arguments) {
vprintf(format, $0)
}
}
func test_varArgs0() {
// CHECK: The answer to life and everything is 42, 42, -42, 3.14
my_printf(
"The answer to life and everything is %ld, %u, %d, %f\n",
42, UInt32(42), Int16(-42), 3.14159279)
}
test_varArgs0()
func test_varArgs1() {
var args = [CVarArg]()
var format = "dig it: "
for i in 0..<12 {
args.append(Int16(-i))
args.append(Float(i))
format += "%d %2g "
}
// CHECK: dig it: 0 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 -11 11
_ = withVaList(args) {
vprintf(format + "\n", $0)
}
}
test_varArgs1()
func test_varArgs3() {
var args = [CVarArg]()
let format = "pointers: '%p' '%p' '%p' '%p' '%p'\n"
args.append(OpaquePointer(bitPattern: 0x1234_5670)!)
args.append(OpaquePointer(bitPattern: 0x1234_5671)!)
args.append(UnsafePointer<Int>(bitPattern: 0x1234_5672)!)
args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5673)!)
#if _runtime(_ObjC)
args.append(AutoreleasingUnsafeMutablePointer<AnyObject>(
UnsafeMutablePointer<AnyObject>(bitPattern: 0x1234_5674)!))
#else
//Linux does not support AutoreleasingUnsafeMutablePointer; put placeholder.
args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5674)!)
#endif
// CHECK: {{pointers: '(0x)?0*12345670' '(0x)?0*12345671' '(0x)?0*12345672' '(0x)?0*12345673' '(0x)?0*12345674'}}
_ = withVaList(args) {
vprintf(format, $0)
}
}
test_varArgs3()
func test_varArgs4() {
// Verify alignment of va_list contents.
// On some architectures some types are better-
// aligned than Int and must be packaged with care.
let i8 = Int8(1)
let i16 = Int16(2)
let i32 = Int32(3)
let i64 = 4444444444444444 as Int64
let u8 = UInt8(10)
let u16 = UInt16(20)
let u32 = UInt32(30)
let u64 = 4040404040404040 as UInt64
let f32 = Float(1.1)
let f64 = Double(2.2)
let fCG = CGFloat(3.3)
my_printf("a %g %d %g %d %g %d a\n", f32, i8, f64, i8, fCG, i8)
my_printf("b %d %g %d %g %d %g %d b\n", i8, f32, i8, f64, i8, fCG, i8)
my_printf("c %d %d %d %d %d %lld %d c\n", i8, i16, i8, i32, i8, i64, i8)
my_printf("d %d %d %d %d %d %d %lld %d d\n",i8, i8, i16, i8, i32, i8, i64, i8)
my_printf("e %u %u %u %u %u %llu %u e\n", u8, u16, u8, u32, u8, u64, u8)
my_printf("f %u %u %u %u %u %u %llu %u f\n",u8, u8, u16, u8, u32, u8, u64, u8)
// CHECK: a 1.1 1 2.2 1 3.3 1 a
// CHECK: b 1 1.1 1 2.2 1 3.3 1 b
// CHECK: c 1 2 1 3 1 4444444444444444 1 c
// CHECK: d 1 1 2 1 3 1 4444444444444444 1 d
// CHECK: e 10 20 10 30 10 4040404040404040 10 e
// CHECK: f 10 10 20 10 30 10 4040404040404040 10 f
}
test_varArgs4()
func test_varArgs5() {
var args = [CVarArg]()
// Confirm the absence of a bug (on x86-64) wherein floats were stored in
// the GP register-save area after the SSE register-save area was
// exhausted, rather than spilling into the overflow argument area.
//
// This is not caught by test_varArgs1 above, because it exhauses the
// GP register-save area before the SSE area.
var format = "rdar-32547102: "
for i in 0..<12 {
args.append(Float(i))
format += "%.1f "
}
// CHECK: rdar-32547102: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0
_ = withVaList(args) {
vprintf(format + "\n", $0)
}
}
test_varArgs5()
func test_varArgs6() {
// Verify alignment of va_list contents when `Float80` is present.
let i8 = Int8(1)
let f32 = Float(1.1)
let f64 = Double(2.2)
#if !os(Windows) && (arch(i386) || arch(x86_64))
let f80 = Float80(4.5)
my_printf("a %g %d %g %d %Lg %d %g a\n", f32, i8, f64, i8, f80, i8, f32)
my_printf("b %d %g %d %g %d %Lg %d %g b\n", i8, f32, i8, f64, i8, f80, i8, f32)
#else // just a dummy to make FileCheck happy, since it ignores `#if`s
let dummy = Double(4.5)
my_printf("a %g %d %g %d %g %d %g a\n", f32, i8, f64, i8, dummy, i8, f32)
my_printf("b %d %g %d %g %d %g %d %g b\n", i8, f32, i8, f64, i8, dummy, i8, f32)
#endif
// CHECK: a 1.1 1 2.2 1 4.5 1 1.1 a
// CHECK: b 1 1.1 1 2.2 1 4.5 1 1.1 b
}
test_varArgs6()
// CHECK: done.
print("done.")
| apache-2.0 | 06bdc1facbbe4b486ea087721d03d397 | 29.205128 | 115 | 0.609083 | 2.594714 | false | true | false | false |
turingcorp/kitkat | kitkat/Controller/CParent.swift | 1 | 1379 | import UIKit
class CParent:UIViewController
{
private var statusBarStyle:UIStatusBarStyle = UIStatusBarStyle.Default
override func viewDidLoad()
{
super.viewDidLoad()
let game:CGame = CGame()
addChildViewController(game)
view.addSubview(game.view)
game.didMoveToParentViewController(self)
let views:[String:AnyObject] = [
"child":game.view]
let metrics:[String:AnyObject] = [:]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-0-[child]-0-|",
options:[],
metrics:metrics,
views:views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[child]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return statusBarStyle
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
//MARK: public
func statusBarLight()
{
statusBarStyle = UIStatusBarStyle.LightContent
setNeedsStatusBarAppearanceUpdate()
}
func statusBarDefault()
{
statusBarStyle = UIStatusBarStyle.Default
setNeedsStatusBarAppearanceUpdate()
}
} | mit | 0df835d69e28c19d3c42e5348f5387c7 | 23.642857 | 75 | 0.594634 | 6.021834 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift | 2 | 2588 | //
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
@usableFromInline
struct BatchedCollectionIndex<Base: Collection> {
let range: Range<Base.Index>
}
extension BatchedCollectionIndex: Comparable {
@usableFromInline
static func == <Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
lhs.range.lowerBound == rhs.range.lowerBound
}
@usableFromInline
static func < <Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
lhs.range.lowerBound < rhs.range.lowerBound
}
}
protocol BatchedCollectionType: Collection {
associatedtype Base: Collection
}
@usableFromInline
struct BatchedCollection<Base: Collection>: Collection {
let base: Base
let size: Int
@usableFromInline
init(base: Base, size: Int) {
self.base = base
self.size = size
}
@usableFromInline
typealias Index = BatchedCollectionIndex<Base>
private func nextBreak(after idx: Base.Index) -> Base.Index {
self.base.index(idx, offsetBy: self.size, limitedBy: self.base.endIndex) ?? self.base.endIndex
}
@usableFromInline
var startIndex: Index {
Index(range: self.base.startIndex..<self.nextBreak(after: self.base.startIndex))
}
@usableFromInline
var endIndex: Index {
Index(range: self.base.endIndex..<self.base.endIndex)
}
@usableFromInline
func index(after idx: Index) -> Index {
Index(range: idx.range.upperBound..<self.nextBreak(after: idx.range.upperBound))
}
@usableFromInline
subscript(idx: Index) -> Base.SubSequence {
self.base[idx.range]
}
}
extension Collection {
@inlinable
func batched(by size: Int) -> BatchedCollection<Self> {
BatchedCollection(base: self, size: size)
}
}
| mit | 5d42213bf37d62232b8c9dca46d48539 | 30.938272 | 217 | 0.73792 | 4.106349 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Nodes/Playback/Samplers/Apple Sampler/AppleSampler.swift | 1 | 10855 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Sampler audio generation.
///
/// 1. init the audio unit like this: var sampler = AppleSampler()
/// 2. load a sound a file: sampler.loadWav("path/to/your/sound/file/in/app/bundle") (without wav extension)
/// 3. connect to the engine: engine.output = sampler
/// 4. start the engine engine.start()
///
open class AppleSampler: Node {
// MARK: - Properties
/// Internal audio unit
public private(set) var internalAU: AUAudioUnit?
private var _audioFiles: [AVAudioFile] = []
/// Audio files to use in the sampler
public var audioFiles: [AVAudioFile] {
get {
return _audioFiles
}
set {
do {
try loadAudioFiles(newValue)
} catch {
Log("Could not load audio files")
}
}
}
fileprivate var token: AUParameterObserverToken?
/// Sampler AV Audio Unit
public var samplerUnit = AVAudioUnitSampler()
/// Tuning amount in semitones, from -24.0 to 24.0, Default: 0.0
/// Doesn't transpose by playing another note (and the accoring zone and layer)
/// but bends the sound up and down like tuning.
public var tuning: AUValue {
get {
return AUValue(samplerUnit.globalTuning / 100.0)
}
set {
samplerUnit.globalTuning = Float(newValue * 100.0)
}
}
// MARK: - Initializers
/// Initialize the sampler node
public init(file: String? = nil) {
super.init(avAudioNode: AVAudioNode())
avAudioUnit = samplerUnit
avAudioNode = samplerUnit
internalAU = samplerUnit.auAudioUnit
if let newFile = file {
do {
try loadWav(newFile)
} catch {
Log("Could not load \(newFile)")
}
}
}
/// Utility method to find a file either in the main bundle or at an absolute path
internal func findFileURL(_ path: String, withExtension ext: String) -> URL? {
if path.hasPrefix("/") && FileManager.default.fileExists(atPath: path + "." + ext) {
return URL(fileURLWithPath: path + "." + ext)
} else if let url = Bundle.main.url(forResource: path, withExtension: ext) {
return url
}
return nil
}
/// Load a wav file
///
/// - parameter file: Name of the file without an extension (assumed to be accessible from the bundle)
///
public func loadWav(_ file: String) throws {
guard let url = findFileURL(file, withExtension: "wav") else {
Log("WAV file not found.")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: [url])
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading wav file at \(url)")
throw error
}
}
/// Load an EXS24 sample data file
///
/// - parameter file: Name of the EXS24 file without the .exs extension
///
public func loadEXS24(_ file: String) throws {
try loadInstrument(file, type: "exs")
}
/// Load an AVAudioFile
///
/// - parameter file: an AVAudioFile
///
public func loadAudioFile(_ file: AVAudioFile) throws {
_audioFiles = [file]
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: [file.url])
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading audio file \"\(file.url.lastPathComponent)\"")
throw error
}
}
/// Load an array of AVAudioFiles
///
/// - parameter files: An array of AVAudioFiles
///
/// If a file name ends with a note name (ex: "violinC3.wav")
/// The file will be set to this note
/// Handy to set multi-sampled instruments or a drum kit...
public func loadAudioFiles(_ files: [AVAudioFile] ) throws {
_audioFiles = files
let urls = files.map { $0.url }
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: urls)
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading audio files \(urls)")
throw error
}
}
/// Load a file path. The sampler can be configured by loading
/// instruments from different types of files such as an aupreset, a DLS or SF2 sound bank,
/// an EXS24 instrument, a single audio file, or an array of audio files.
///
/// - parameter filePath: Name of the file with the extension
///
public func loadPath(_ filePath: String) throws {
do {
try ExceptionCatcher {
try self.samplerUnit.loadInstrument(at: URL(fileURLWithPath: filePath))
self.samplerUnit.reset()
}
} catch {
Log("Error Sampler.loadPath loading file at \(filePath)")
throw error
}
}
internal func loadInstrument(_ file: String, type: String) throws {
//Log("filename is \(file)")
guard let url = findFileURL(file, withExtension: type) else {
Log("File not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try ExceptionCatcher {
try self.samplerUnit.loadInstrument(at: url)
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading instrument resource \(file)")
throw error
}
}
/// Output Amplitude. Range: -90.0 -> +12 db, Default: 0 db
public var amplitude: AUValue = 0 {
didSet {
samplerUnit.masterGain = Float(amplitude)
}
}
/// Normalized Output Volume. Range: 0 -> 1, Default: 1
public var volume: AUValue = 1 {
didSet {
let newGain = volume.denormalized(to: -90.0 ... 0.0)
samplerUnit.masterGain = Float(newGain)
}
}
/// Pan. Range: -1 -> 1, Default: 0
public var pan: AUValue = 0 {
didSet {
samplerUnit.stereoPan = Float(100.0 * pan)
}
}
// MARK: - Playback
/// Play a MIDI Note or trigger a sample
///
/// - Parameters:
/// - noteNumber: MIDI Note Number to play
/// - velocity: MIDI Velocity
/// - channel: MIDI Channnel
///
/// NB: when using an audio file, noteNumber 60 will play back the file at normal
/// speed, 72 will play back at double speed (1 octave higher), 48 will play back at
/// half speed (1 octave lower) and so on
public func play(noteNumber: MIDINoteNumber = 60,
velocity: MIDIVelocity = 127,
channel: MIDIChannel = 0) throws {
self.samplerUnit.startNote(noteNumber, withVelocity: velocity, onChannel: channel)
}
/// Stop a MIDI Note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number to stop
/// - channel: MIDI Channnel
///
public func stop(noteNumber: MIDINoteNumber = 60, channel: MIDIChannel = 0) throws {
try ExceptionCatcher {
self.samplerUnit.stopNote(noteNumber, onChannel: channel)
}
}
// MARK: - SoundFont Support
// NOTE: The following methods might seem like they belong in the
// SoundFont extension, but when place there, iOS12 beta crashed
fileprivate func loadSoundFont(_ file: String, preset: Int, type: Int) throws {
guard let url = findFileURL(file, withExtension: "sf2") else {
Log("Soundfont file not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try samplerUnit.loadSoundBankInstrument(
at: url,
program: MIDIByte(preset),
bankMSB: MIDIByte(type),
bankLSB: MIDIByte(kAUSampler_DefaultBankLSB))
samplerUnit.reset()
} catch let error as NSError {
Log("Error loading SoundFont \(file)")
throw error
}
}
/// Load a Bank from a SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
/// - bank: Number of the bank to use
///
public func loadSoundFont(_ file: String, preset: Int, bank: Int) throws {
guard let url = findFileURL(file, withExtension: "sf2") else {
Log("Soundfont file not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
var bMSB: Int
if bank <= 127 {
bMSB = kAUSampler_DefaultMelodicBankMSB
} else {
bMSB = kAUSampler_DefaultPercussionBankMSB
}
let bLSB: Int = bank % 128
try samplerUnit.loadSoundBankInstrument(
at: url,
program: MIDIByte(preset),
bankMSB: MIDIByte(bMSB),
bankLSB: MIDIByte(bLSB))
samplerUnit.reset()
} catch let error as NSError {
Log("Error loading SoundFont \(file)")
throw error
}
}
/// Load a Melodic SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
///
public func loadMelodicSoundFont(_ file: String, preset: Int) throws {
try loadSoundFont(file, preset: preset, type: kAUSampler_DefaultMelodicBankMSB)
}
/// Load a Percussive SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
///
public func loadPercussiveSoundFont(_ file: String, preset: Int = 0) throws {
try loadSoundFont(file, preset: preset, type: kAUSampler_DefaultPercussionBankMSB)
}
/// Set the pitch bend amount
/// - Parameters:
/// - amount: Value of the pitch bend
/// - channel: MIDI Channel ot apply the bend to
public func setPitchbend(amount: MIDIWord, channel: MIDIChannel) {
samplerUnit.sendPitchBend(amount, onChannel: channel)
}
/// Reset the internal sampler
public func resetSampler() {
samplerUnit.reset()
}
}
| mit | 9551ddf8849aedaae34433ed26dfb017 | 32.816199 | 108 | 0.579088 | 4.470758 | false | false | false | false |
eaplatanios/swift-rl | Sources/ReinforcementLearning/Utilities/General.swift | 1 | 4284 | // Copyright 2019, Emmanouil Antonios Platanios. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import Foundation
import TensorFlow
#if os(Linux)
import FoundationNetworking
#endif
public typealias TensorFlowSeed = (graph: Int32, op: Int32)
public enum ReinforcementLearningError: Error {
case renderingError(String)
}
public struct Empty: Differentiable, KeyPathIterable {
public init() {}
}
public protocol Copyable {
func copy() -> Self
}
public extension Encodable {
func json(pretty: Bool = true) throws -> String {
let encoder = JSONEncoder()
if pretty {
encoder.outputFormatting = .prettyPrinted
}
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)!
}
}
public extension Decodable {
init(fromJson json: String) throws {
let jsonDecoder = JSONDecoder()
self = try jsonDecoder.decode(Self.self, from: json.data(using: .utf8)!)
}
}
/// Downloads the file at `url` to `path`, if `path` does not exist.
///
/// - Parameters:
/// - from: URL to download data from.
/// - to: Destination file path.
///
/// - Returns: Boolean value indicating whether a download was
/// performed (as opposed to not needed).
public func maybeDownload(from url: URL, to destination: URL) throws {
if !FileManager.default.fileExists(atPath: destination.path) {
// Create any potentially missing directories.
try FileManager.default.createDirectory(
atPath: destination.deletingLastPathComponent().path,
withIntermediateDirectories: true)
// Create the URL session that will be used to download the dataset.
let semaphore = DispatchSemaphore(value: 0)
let delegate = DataDownloadDelegate(destinationFileUrl: destination, semaphore: semaphore)
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
// Download the data to a temporary file and then copy that file to
// the destination path.
print("Downloading \(url).")
let task = session.downloadTask(with: url)
task.resume()
// Wait for the download to finish.
semaphore.wait()
}
}
internal class DataDownloadDelegate: NSObject, URLSessionDownloadDelegate {
let destinationFileUrl: URL
let semaphore: DispatchSemaphore
let numBytesFrequency: Int64
internal var logCount: Int64 = 0
init(
destinationFileUrl: URL,
semaphore: DispatchSemaphore,
numBytesFrequency: Int64 = 1024 * 1024
) {
self.destinationFileUrl = destinationFileUrl
self.semaphore = semaphore
self.numBytesFrequency = numBytesFrequency
}
internal func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) -> Void {
if (totalBytesWritten / numBytesFrequency > logCount) {
let mBytesWritten = String(format: "%.2f", Float(totalBytesWritten) / (1024 * 1024))
if totalBytesExpectedToWrite > 0 {
let mBytesExpectedToWrite = String(
format: "%.2f", Float(totalBytesExpectedToWrite) / (1024 * 1024))
print("Downloaded \(mBytesWritten) MBs out of \(mBytesExpectedToWrite).")
} else {
print("Downloaded \(mBytesWritten) MBs.")
}
logCount += 1
}
}
internal func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL
) -> Void {
logCount = 0
do {
try FileManager.default.moveItem(at: location, to: destinationFileUrl)
} catch (let writeError) {
print("Error writing file \(location.path) : \(writeError)")
}
print("The file was downloaded successfully to \(location.path).")
semaphore.signal()
}
}
| apache-2.0 | 1770100b128dbd6fe1998da0a7362477 | 30.5 | 94 | 0.706349 | 4.476489 | false | false | false | false |
johnno1962d/swift | test/Reflection/typeref_lowering.swift | 1 | 5484 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %S/Inputs/TypeLowering.swift -parse-as-library -emit-module -emit-library -module-name TypeLowering -Xfrontend -enable-reflection-metadata -Xfrontend -enable-reflection-names -o %t/libTypesToReflect
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect -binary-filename %platform-module-dir/libswiftCore.dylib -dump-type-lowering < %s | FileCheck %s
// REQUIRES: OS=macosx
V12TypeLowering11BasicStruct
// CHECK: (struct TypeLowering.BasicStruct)
// CHECK-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-NEXT: (field name=i1 offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=i2 offset=2
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=i3 offset=4
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=bi1 offset=8
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=bi2 offset=10
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=bi3 offset=12
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
V12TypeLowering15AssocTypeStruct
// CHECK: (struct TypeLowering.AssocTypeStruct)
// CHECK-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field name=t offset=0
// CHECK-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field name=a offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=b offset=2
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=c offset=4
// CHECK-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field offset=2
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))))))))
TGV12TypeLowering3BoxVs5Int16_Vs5Int32_
// CHECK-NEXT: (tuple
// CHECK-NEXT: (bound_generic_struct TypeLowering.Box
// CHECK-NEXT: (struct Swift.Int16))
// CHECK-NEXT: (struct Swift.Int32))
// CHECK-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field offset=4
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
| apache-2.0 | 0c156f502fb1e201af62ff3d965f9081 | 60.617978 | 226 | 0.654814 | 3.337797 | false | false | false | false |
archembald/avajo-ios | avajo-ios/FetchedResultsTableViewController.swift | 5 | 6035 | // Copyright (c) 2014-2015 Martijn Walraven
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
import Meteor
class FetchedResultsTableViewController: UITableViewController, ContentLoading, SubscriptionLoaderDelegate, FetchedResultsTableViewDataSourceDelegate {
// MARK: - Lifecycle
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Model
var managedObjectContext: NSManagedObjectContext!
func saveManagedObjectContext() {
var error: NSError?
do {
try managedObjectContext!.save()
} catch let error1 as NSError {
error = error1
print("Encountered error saving managed object context: \(error)")
}
}
// MARK: - View Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
updatePlaceholderView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadContentIfNeeded()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
placeholderView?.frame = tableView.bounds
}
// MARK: - Content Loading
private(set) var contentLoadingState: ContentLoadingState = .Initial {
didSet {
if isViewLoaded() {
updatePlaceholderView()
}
}
}
var isContentLoaded: Bool {
switch contentLoadingState {
case .Loaded:
return true
default:
return false
}
}
private(set) var needsLoadContent: Bool = true
func setNeedsLoadContent() {
needsLoadContent = true
if isViewLoaded() {
loadContentIfNeeded()
}
}
func loadContentIfNeeded() {
if needsLoadContent {
loadContent()
}
}
func loadContent() {
needsLoadContent = false
subscriptionLoader = SubscriptionLoader()
subscriptionLoader!.delegate = self
configureSubscriptionLoader(subscriptionLoader!)
subscriptionLoader!.whenReady { [weak self] in
self?.setUpDataSource()
self?.contentLoadingState = .Loaded
}
if !subscriptionLoader!.isReady {
if Meteor.connectionStatus == .Offline {
contentLoadingState = .Offline
} else {
contentLoadingState = .Loading
}
}
}
func resetContent() {
dataSource = nil
tableView.dataSource = nil
tableView.reloadData()
subscriptionLoader = nil
contentLoadingState = .Initial
}
private var subscriptionLoader: SubscriptionLoader?
func configureSubscriptionLoader(subscriptionLoader: SubscriptionLoader) {
}
var dataSource: FetchedResultsTableViewDataSource!
func setUpDataSource() {
if let fetchedResultsController = createFetchedResultsController() {
dataSource = FetchedResultsTableViewDataSource(tableView: tableView, fetchedResultsController: fetchedResultsController)
dataSource.delegate = self
tableView.dataSource = dataSource
dataSource.performFetch()
}
}
func createFetchedResultsController() -> NSFetchedResultsController? {
return nil
}
// MARK: SubscriptionLoaderDelegate
func subscriptionLoader(subscriptionLoader: SubscriptionLoader, subscription: METSubscription, didFailWithError error: NSError) {
contentLoadingState = .Error(error)
}
// MARK: Connection Status Notification
func connectionStatusDidChange() {
if !isContentLoaded && Meteor.connectionStatus == .Offline {
contentLoadingState = .Offline
}
}
// MARK: - User
var currentUser: User? {
if let userID = Meteor.userID {
let userObjectID = Meteor.objectIDForDocumentKey(METDocumentKey(collectionName: "users", documentID: userID))
return (try? managedObjectContext.existingObjectWithID(userObjectID)) as? User
}
return nil;
}
// MARK: - Placeholder View
private var placeholderView: PlaceholderView?
private var savedCellSeparatorStyle: UITableViewCellSeparatorStyle = .None
func updatePlaceholderView() {
if isContentLoaded {
if placeholderView != nil {
placeholderView?.removeFromSuperview()
placeholderView = nil
swap(&savedCellSeparatorStyle, &tableView.separatorStyle)
}
} else {
if placeholderView == nil {
placeholderView = PlaceholderView()
tableView.addSubview(placeholderView!)
swap(&savedCellSeparatorStyle, &tableView.separatorStyle)
}
}
switch contentLoadingState {
case .Loading:
placeholderView?.showLoadingIndicator()
case .Offline:
placeholderView?.showTitle("Could not establish connection to server", message: nil)
case .Error(let error):
placeholderView?.showTitle(error.localizedDescription, message: error.localizedFailureReason)
default:
break
}
}
// MARK: - FetchedResultsTableViewDataSourceDelegate
func dataSource(dataSource: FetchedResultsTableViewDataSource, didFailWithError error: NSError) {
print("Data source encountered error: \(error)")
}
}
| agpl-3.0 | e85da676448c64118e2b4064914253ba | 27.601896 | 151 | 0.707208 | 5.29386 | false | false | false | false |
MounikaAnkam/BooksAuthors | BooksAuthors/NewAuthorViewController.swift | 1 | 2683 | //
// NewAuthorViewController.swift
// BooksAuthors
//
// Created by Jaini,Santhoshi on 3/20/15.
// Copyright (c) 2015 Student. All rights reserved.
//
import UIKit
import CoreData
class NewAuthorViewController: UIViewController , UITextFieldDelegate{
var managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
@IBOutlet weak var SSNTF: UITextField!
@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var dobTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
SSNTF.placeholder = "Enter SSN "
dobTF.placeholder = "MM-DD-YYYY"
nameTF.placeholder = "Enter Name"
nameTF.delegate = self
SSNTF.delegate = self
dobTF.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Done(sender: AnyObject) {
var newAuthor = NSEntityDescription.insertNewObjectForEntityForName("Author",
inManagedObjectContext: managedObjectContext!) as Author
if !dobTF.text.isEmpty && !nameTF.text.isEmpty && !SSNTF.text.isEmpty {
newAuthor.ssn = Int((SSNTF.text as NSString).integerValue)
newAuthor.name = nameTF.text
var dateString = dobTF.text
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateFromString = dateFormatter.dateFromString(dateString)
newAuthor.dob = dateFromString!
var error:NSError?
managedObjectContext?.save(&error)
self.dismissViewControllerAnimated(true , completion: nil )
}
}
@IBAction func Cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true , completion: nil )
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
nameTF.resignFirstResponder()
SSNTF.resignFirstResponder()
dobTF.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 629b07efc75b6320993d829880b2e033 | 26.947917 | 111 | 0.632501 | 5.189555 | false | false | false | false |
SnowdogApps/Project-Needs-Partner | CooperationFinder/ViewModels/SDProjectsListViewModel.swift | 1 | 3958 | //
// SDProjectsListViewModel.swift
// CooperationFinder
//
// Created by Radoslaw Szeja on 25.02.2015.
// Copyright (c) 2015 Snowdog. All rights reserved.
//
import UIKit
protocol SDListProtocol {
func numberOfSectionsAtIndexPath() -> Int
func numberOfRowsInSection(section: Int) -> Int
func itemAtIndexpath(indexPath: NSIndexPath) -> Project?
}
protocol SDListViewModelDelegate : class {
func didReloadData(count: Int)
}
class SDProjectsListViewModel: NSObject, SDListProtocol {
var tags : [String]?
var status : String?
var trustedOnly : Bool?
var commercial : Bool?
var loggedUser : User?
var itemsArray: [AnyObject] = []
var searchItemsArray: [AnyObject] = []
private var queryIndex = 0;
private var searchQueryIndex = 0;
weak private var delegate: SDListViewModelDelegate?
override init() {
self.delegate = nil
super.init()
}
init(delegate: SDListViewModelDelegate) {
self.delegate = delegate
super.init()
}
func reloadData(searchQuery: String) {
self.queryIndex++
let q = self.queryIndex
let getProjectsBlock : () -> Void = {
Project.getProjects(nil, searchPhrase:searchQuery, tags: self.tags, statuses: self.statuses(), commercial: self.commercial, partner: self.trustedOnly) { (success, projects) -> Void in
if let projs = projects {
self.itemsArray = projs
} else {
self.itemsArray = []
}
Async.main {
if (q == self.queryIndex) {
if let del = self.delegate {
del.didReloadData(self.itemsArray.count)
}
}
}
}
}
if (self.loggedUser != nil) {
getProjectsBlock()
} else {
User.getLoggedUser(completion: { (user) -> () in
self.loggedUser = user
getProjectsBlock()
})
}
}
func statuses() -> [String] {
var statuses : [String] = []
if self.status != nil {
statuses.append(self.status!)
} else {
statuses.append(ProjectStatusOpen)
if let user = self.loggedUser {
if (user.role == UserRoleModerator) {
statuses.append(ProjectStatusWaitingForApproval)
}
}
}
return statuses
}
// MARK: SDListProtocol
func numberOfSectionsAtIndexPath() -> Int {
return 1
}
func numberOfRowsInSection(section: Int) -> Int {
if section == 0 {
return itemsArray.count
}
return 0
}
func numberOfRowsInSearchSection(section: Int) -> Int {
if section == 0 {
return searchItemsArray.count
}
return 0
}
func itemAtIndexpath(indexPath: NSIndexPath) -> Project? {
return itemsArray[indexPath.row] as? Project
}
func searchItemAtIndexPath(indexPath:NSIndexPath) -> Project? {
return searchItemsArray[indexPath.row] as? Project
}
func searchWithPhrase(phrase: String, completion: (success: Bool) -> ()) {
self.searchQueryIndex++
let q = self.searchQueryIndex
Project.getProjects(nil, searchPhrase:phrase, tags: nil, statuses: self.statuses(), commercial: nil, partner: nil) { (success, projects) -> Void in
if let projs = projects {
self.searchItemsArray = projs
} else {
self.searchItemsArray = []
}
Async.main {
if (q == self.searchQueryIndex) {
completion(success: success)
}
}
}
}
}
| apache-2.0 | 41cc2877fa6e72647e6e65a0faee45f4 | 27.070922 | 195 | 0.535624 | 4.82095 | false | false | false | false |
fespinoza/linked-ideas-osx | LinkedIdeas-Shared/Sources/ViewModels/DrawableLink.swift | 1 | 2219 | //
// DrawableLink.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 16/02/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
import CoreGraphics
import Foundation
public struct DrawableLink: DrawableElement {
let link: Link
public init(link: Link) {
self.link = link
}
public var drawingBounds: CGRect {
return CGRect(point1: link.originPoint, point2: link.targetPoint)
}
public func draw() {
link.color.set()
constructArrow()?.bezierPath().fill()
drawSelectedRing()
drawLinkText()
drawForDebug()
}
func drawLinkText() {
guard link.stringValue != "" else {
return
}
// background
Color.white.set()
var textSize = link.attributedStringValue.size()
let padding: CGFloat = 8.0
textSize.width += padding
textSize.height += padding
let textRect = CGRect(center: link.centerPoint, size: textSize)
textRect.fill()
// text
let bottomLeftTextPoint = link.centerPoint.translate(
deltaX: -(textSize.width - padding) / 2.0,
deltaY: -(textSize.height - padding) / 2.0
)
// swiftlint:disable:next force_cast
let attributedStringValue = link.attributedStringValue.mutableCopy() as! NSMutableAttributedString
attributedStringValue.addAttributes(
[.foregroundColor: Color.gray],
range: NSRangeFromString(link.attributedStringValue.string)
)
attributedStringValue.draw(at: bottomLeftTextPoint)
}
func drawSelectedRing() {
guard link.isSelected else {
return
}
Color.red.set()
constructArrow()?.bezierPath().stroke()
}
func constructArrow() -> Arrow? {
let originPoint = link.originPoint
let targetPoint = link.targetPoint
if let intersectionPointWithOrigin = link.originRect.firstIntersectionTo(targetPoint),
let intersectionPointWithTarget = link.targetRect.firstIntersectionTo(originPoint) {
return Arrow(point1: intersectionPointWithOrigin, point2: intersectionPointWithTarget)
} else {
return nil
}
}
public func drawForDebug() {
if isDebugging() {
drawDebugHelpers()
Color.magenta.set()
BezierPath(rect: link.area).stroke()
}
}
}
| mit | 7ef46a34804610317134149eff2ce878 | 24.204545 | 102 | 0.686204 | 4.265385 | false | false | false | false |
AMarones/AMPickerView | Sample/Sample/MultiplesPickersViewController.swift | 1 | 2163 | //
// MultiplesPickersViewController.swift
// Sample
//
// Created by Alexandre Marones on 11/10/15.
//
//
import UIKit
class MultiplesPickersViewController: UIViewController , AMPickerViewDelegate {
@IBOutlet weak var buttonSelectValue: UIButton!
@IBOutlet weak var buttonSelectCard: UIButton!
private var _cards = ["•••• 5858", "•••• 4444", "•••• 3269", "•••• 1109"]
private var _values = ["$10", "$20", "$35", "$60"]
private var _datasource = [String]()
private let _sentByValues = "values"
private let _sentByCards = "cards"
private var _sentBy = String()
private var _alertPickerView = AMPickerView()
override func viewDidLoad() {
super.viewDidLoad()
_alertPickerView = AMPickerView(delegate: self, ownerViewControler: self)
}
func showPickerView() {
var pickerTitle = "Select Card"
if _sentBy == _sentByValues {
pickerTitle = "Select Value"
}
_alertPickerView.show(pickerTitle, datasource: _datasource)
}
// MARK: - IBAction
@IBAction func selectValueButtonPressed(sender: AnyObject) {
_datasource.removeAll(keepCapacity: false)
_datasource = _values
_sentBy = _sentByValues
showPickerView()
}
@IBAction func selectCardButtonPressed(sender: AnyObject) {
_datasource.removeAll(keepCapacity: false)
_datasource = _cards
_sentBy = _sentByCards
showPickerView()
}
// MARK: - AMActionPickerViewDelegate
func cancelButtonPressed() {
_alertPickerView.close()
}
func doneButtonPressed(index: Int) {
let selectedValue = _datasource[index]
if _sentBy == _sentByValues {
buttonSelectValue.setTitle(selectedValue, forState: UIControlState.Normal)
} else {
buttonSelectCard.setTitle(selectedValue, forState: UIControlState.Normal)
}
_alertPickerView.close()
}
}
| mit | 060fde3cab0af1fb0236d84b660049fa | 25.6375 | 87 | 0.586579 | 4.683516 | false | false | false | false |
peferron/algo | EPI/Parallel Computing/The readers-writers problem/swift/test.swift | 1 | 511 | if #available(OSX 10.10, *) {
var expected = 1
for _ in 0...50000 {
if arc4random_uniform(2) == 0 {
write()
expected += 1
} else {
read()
}
}
concurrentQueue.sync(execute: DispatchWorkItem(qos: .default, flags: .barrier) {
guard data == expected else {
print("Expected data to be \(expected), but was \(data)")
exit(1)
}
})
} else {
print("Requires OS X 10.10 or newer")
exit(1)
}
| mit | 47e7600681223112a85e9836bf85d23a | 22.227273 | 84 | 0.48728 | 3.930769 | false | false | false | false |
coppercash/Anna | CoreJS/Module.swift | 1 | 5749 | //
// Module.swift
// Anna_iOS
//
// Created by William on 2018/6/27.
//
import Foundation
import JavaScriptCore
class
Module
{
let
fileManager :FileManaging,
core :Set<String>,
global :Set<URL>
init(
fileManager :FileManaging,
core :Set<String>,
global :Set<URL>
) {
self.fileManager = fileManager
self.core = core
self.global = global
}
func
resolve(
x :String,
from module :URL?
) throws -> String {
let
core = self.core
if core.contains(x) {
return x
}
//
// x is not a core module
let
isAbsolute = x.hasPrefix("/"),
base :URL
if isAbsolute {
base = URL(fileURLWithPath: "/")
}
else {
guard let module = module
else { throw ResolveError.noBase }
base = module
}
guard isAbsolute
|| x.hasPrefix("./")
|| x.hasPrefix("../")
else {
let
resolved = try self.resolve(
nodeModule: x,
with: base.deletingLastPathComponent()
).standardized.path
return resolved
}
//
// x is not a node module
let
absolute = base.appendingPathComponent(
isAbsolute ? String(x.dropFirst()) : x
)
guard
let
resolved =
(try? self.resolve(file: absolute))
?? (try? self.resolve(directory: absolute))
else { throw ResolveError.notFound }
return resolved.standardized.path
}
func
resolve(
file :URL
) throws -> URL {
let
fs = self.fileManager
var
isDirecotry = false as ObjCBool
if fs.fileExists(
atPath: file.path,
isDirectory: &isDirecotry
) {
if isDirecotry.boolValue == false {
return file
}
}
return try self.resolve(
file: file,
extending: ["js", "json", "node"]
)
}
func
resolve(
file :URL,
extending extensions:[String]
) throws -> URL {
let
fs = self.fileManager
for ext in extensions {
let
extended = file.appendingPathExtension(ext)
var
isDirecotry = false as ObjCBool
if fs.fileExists(
atPath: extended.path,
isDirectory: &isDirecotry
) {
if isDirecotry.boolValue == false {
return extended
}
}
}
throw ResolveError.notFound
}
func
resolve(
directory :URL
) throws -> URL {
return try self.resolveIndex(in: directory)
}
func
resolveIndex(
in directory :URL
) throws -> URL {
return try self.resolve(
file: directory.appendingPathComponent("index"),
extending: ["js", "json", "node"]
)
}
func
resolve(
nodeModule :String,
with start :URL
) throws -> URL {
let
dirs = self.nodeModulesPaths(with: start)
for dir in dirs {
let
absolute = dir.appendingPathComponent(nodeModule)
if
let
resolved =
(try? resolve(file: absolute))
?? (try? resolve(directory: absolute))
{ return resolved }
}
throw ResolveError.notFound
}
func
nodeModulesPaths(
with start :URL
) -> [URL] {
var
paths = Array(self.global)
func
_backtrack(
_ current :URL,
_ paths : inout [URL]
) {
let
tail = current.lastPathComponent
guard tail != "/"
else { return }
if tail != "node_modules" {
paths.append(current.appendingPathComponent("node_modules"))
}
_backtrack(
current.deletingLastPathComponent(),
&paths
)
}
_backtrack(start, &paths)
return paths
}
func
loadScript(
at url :URL,
to context :JSContext,
exports :JSValue,
require :JSValue,
module :JSValue
) {
let
fs = self.fileManager,
path = url.path
guard
let
data = fs.contents(atPath: path),
let
script = String(data: data, encoding: .utf8)
else
{
context.exception = JSValue(
newErrorFromMessage:
"Cannot read file at path \(path)!).",
in: context
)
return
}
let
decorated = String(format: ("""
(function () { return (
function (exports, require, module, __filename, __dirname) {
%@
}
); })();
"""), script)
let
_ = context
.evaluateScript(
decorated,
withSourceURL: url
)
.call(withArguments: [
exports,
require,
module,
path,
url.deletingLastPathComponent().path
]
)
}
}
enum
ResolveError : Error
{
case noBase, notFound
}
extension String {
func fileURL() -> URL {
return URL(fileURLWithPath: self)
}
}
| mit | 97d67f73bff7962e1167fec40457dbcc | 22.369919 | 76 | 0.451383 | 5.078622 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/UserSession/ZMUserSession+SecurityClassification.swift | 1 | 1606 | //
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
public enum SecurityClassification {
case none
case classified
case notClassified
}
extension ZMUserSession {
public func classification(with users: [UserType]) -> SecurityClassification {
guard isSelfClassified else { return .none }
let isClassified = users.allSatisfy {
classification(with: $0) == .classified
}
return isClassified ? .classified : .notClassified
}
private func classification(with user: UserType) -> SecurityClassification {
guard isSelfClassified else { return .none }
guard let otherDomain = user.domain else { return .notClassified }
return classifiedDomainsFeature.config.domains.contains(otherDomain) ? .classified : .notClassified
}
private var isSelfClassified: Bool {
classifiedDomainsFeature.status == .enabled && selfUser.domain != nil
}
}
| gpl-3.0 | 6c1fd890e9fd1b07ff667b35d876d4fb | 31.12 | 107 | 0.711706 | 4.588571 | false | false | false | false |
benlangmuir/swift | test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift | 14 | 2763 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: VENDOR=apple || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5Value[[UNIQUE_ID_1:[0-9A-Z_]+]]OySiGMf" = linkonce_odr hidden constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** getelementptr inbounds (%swift.enum_vwtable, %swift.enum_vwtable* @"$s4main5Value[[UNIQUE_ID_1]]OySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 513,
// CHECK-SAME: %swift.type_descriptor* bitcast ({{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
fileprivate enum Value<First> {
case first(First)
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s4main5Value[[UNIQUE_ID_1]]OySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: )
// CHECK-SAME: )
// CHECK: }
func doit() {
consume( Value.first(13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]OMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata(
// CHECK-SAME: [[INT]] %0,
// CHECK-SAME: i8* [[ERASED_TYPE]],
// CHECK-SAME: i8* undef,
// CHECK-SAME: i8* undef,
// CHECK-SAME: %swift.type_descriptor* bitcast (
// CHECK-SAME: {{.*}}$s4main5Value[[UNIQUE_ID_1]]OMn{{.*}} to %swift.type_descriptor*
// CHECK-SAME: )
// CHECK-SAME: ) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 775f2866d7184a9ffbc1f1a1968992db | 37.915493 | 157 | 0.592472 | 2.977371 | false | false | false | false |
delba/JASON | Source/JSON.swift | 1 | 4571 | //
// JSON.swift
//
// Copyright (c) 2015-2019 Damien (http://delba.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
// MARK: - Initializers
public struct JSON {
/// The date formatter used for date conversions
public static var dateFormatter = DateFormatter()
/// The object on which any subsequent method operates
public let object: AnyObject?
/**
Creates an instance of JSON from AnyObject.
- parameter object: An instance of any class
- returns: the created JSON
*/
public init(_ object: Any?) {
self.init(object: object)
}
/**
Creates an instance of JSON from NSData.
- parameter data: An instance of NSData
- returns: the created JSON
*/
public init(_ data: Data?) {
self.init(object: JSON.objectWithData(data))
}
/**
Creates an instance of JSON from a string.
- parameter data: A string
- returns: the created JSON
*/
public init(_ string: String?) {
self.init(string?.data(using: String.Encoding.utf8))
}
/**
Creates an instance of JSON from AnyObject.
Takes an explicit parameter name to prevent calls to init(_:) with NSData? when nil is passed.
- parameter object: An instance of any class
- returns: the created JSON
*/
internal init(object: Any?) {
self.object = object as AnyObject?
}
}
// MARK: - Subscript
extension JSON {
/**
Creates a new instance of JSON.
- parameter index: A string
- returns: a new instance of JSON or itself if its object is nil.
*/
public subscript(index: String) -> JSON {
if object == nil { return self }
if let nsDictionary = nsDictionary {
return JSON(nsDictionary[index])
}
return JSON(object: nil)
}
/**
Creates a new instance of JSON.
- parameter index: A string
- returns: a new instance of JSON or itself if its object is nil.
*/
public subscript(index: Int) -> JSON {
if object == nil { return self }
if let nsArray = nsArray {
return JSON(nsArray[safe: index])
}
return JSON(object: nil)
}
/**
Creates a new instance of JSON.
- parameter indexes: Any
- returns: a new instance of JSON or itself if its object is nil
*/
public subscript(path indexes: Any...) -> JSON {
return self[indexes]
}
internal subscript(indexes: [Any]) -> JSON {
if object == nil { return self }
var json = self
for index in indexes {
if let string = index as? String, let object = json.nsDictionary?[string] {
json = JSON(object)
continue
}
if let int = index as? Int, let object = json.nsArray?[safe: int] {
json = JSON(object)
continue
} else {
json = JSON(object: nil)
break
}
}
return json
}
}
// MARK: - Private extensions
private extension JSON {
/**
Converts an instance of NSData to AnyObject.
- parameter data: An instance of NSData or nil
- returns: An instance of AnyObject or nil
*/
static func objectWithData(_ data: Data?) -> Any? {
guard let data = data else { return nil }
return try? JSONSerialization.jsonObject(with: data)
}
}
| mit | 640679c4ece5efbf9fe3c263b33ce5fc | 26.047337 | 102 | 0.611901 | 4.62184 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Components/Controllers/DigitalSignatureVerificationViewController.swift | 1 | 4130 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import Foundation
import WebKit
import WireUtilities
// MARK: - Error states
public enum DigitalSignatureVerificationError: Error {
case postCodeRetry
case authenticationFailed
case otherError
}
class DigitalSignatureVerificationViewController: UIViewController {
typealias DigitalSignatureCompletion = ((_ result: VoidResult) -> Void)
// MARK: - Private Property
private var completion: DigitalSignatureCompletion?
private var webView = WKWebView(frame: .zero)
private var url: URL?
// MARK: - Init
init(url: URL, completion: DigitalSignatureCompletion? = nil) {
self.url = url
self.completion = completion
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
loadURL()
}
// MARK: - Private Method
private func setupWebView() {
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
updateButtonMode()
view.addSubview(webView)
webView.fitIn(view: view)
}
private func updateButtonMode() {
let buttonItem = UIBarButtonItem(title: "general.done".localized,
style: .done,
target: self,
action: #selector(onClose))
buttonItem.accessibilityIdentifier = "DoneButton"
buttonItem.accessibilityLabel = "general.done".localized
buttonItem.tintColor = UIColor.black
navigationItem.leftBarButtonItem = buttonItem
}
private func loadURL() {
guard let url = url else { return }
let request = URLRequest(url: url)
webView.load(request)
}
@objc private func onClose() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - WKNavigationDelegate
extension DigitalSignatureVerificationViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard
let url = navigationAction.request.url,
let response = parseVerificationURL(url)
else {
decisionHandler(.allow)
return
}
switch response {
case .success:
completion?(.success)
decisionHandler(.cancel)
case .failure(let error):
completion?(.failure(error))
decisionHandler(.cancel)
}
}
func parseVerificationURL(_ url: URL) -> VoidResult? {
let urlComponents = URLComponents(string: url.absoluteString)
let postCode = urlComponents?.queryItems?
.first(where: { $0.name == "postCode" })
guard let postCodeValue = postCode?.value else {
return nil
}
switch postCodeValue {
case "sas-success":
return .success
case "sas-error-authentication-failed":
return .failure(DigitalSignatureVerificationError.authenticationFailed)
default:
return .failure(DigitalSignatureVerificationError.otherError)
}
}
}
| gpl-3.0 | c262a259b7e854f2bd97f1e141c295e8 | 30.769231 | 84 | 0.641404 | 5.149626 | false | false | false | false |
sashakid/Chickens | Source/Chickens/Helpers/PriceService.swift | 1 | 2658 | //
// PriceService.swift
// Chickens
//
// Created by Aleksey Gorbachevskiy on 21/03/17.
// Copyright © 2017 Alexander Yakovlev. All rights reserved.
//
import UIKit
import Money
final class PriceService {
static let shared: PriceService = PriceService()
var price: Money {
get {
if let numberPrice = settings!.value(forKey: "Price") as? Double {
return Money(numberPrice)
} else {
return 0
}
}
set {
settings?["Price"] = newValue
}
}
private var settings: NSMutableDictionary? {
get {
if let path = Bundle.main.path(forResource: "Settings", ofType: "plist") {
if let dict = NSMutableDictionary(contentsOfFile: path) {
return dict
}
}
return nil
}
}
func updatePrice() {
if let url = URL.init(string:"https://e-dostavka.by/catalog/item_440852.html") {
if let data = NSData.init(contentsOf: url) {
let doc = TFHpple(htmlData: data as Data!)
if let elements = doc?.search(withXPathQuery: "//div[@class='right']/div[@class='services_wrap']/div[@class='prices_block']/div[@class='price_byn']/div[@class='price']") as? [TFHppleElement] {
for element in elements {
let components = element.content.components(separatedBy:".")
var stringPrice = ""
for (i, component) in components.enumerated() {
if let newComponent = Int(component.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")) {
if component.characters.count > 0 {
switch i {
case 0:
stringPrice.append("\(newComponent).")
case 1:
stringPrice.append("\(newComponent)")
default:
break
}
}
}
}
price = Money(Double(stringPrice)!)
//print("[PriceService]: \(price.formatted(withStyle: .currencyPlural, forLocale: .Belarusian))")
print("[PriceService]: \(price.decimal)")
}
}
}
}
}
}
| mit | 116dea190eceba949119275daa7d3fa6 | 36.422535 | 208 | 0.450884 | 5.389452 | false | false | false | false |
BlenderSleuth/Unlokit | Unlokit/Nodes/Blocks/GlueBlockNode.swift | 1 | 6036 | //
// GlueBlockNode.swift
// Unlokit
//
// Created by Ben Sutherland on 25/1/17.
// Copyright © 2017 blendersleuthdev. All rights reserved.
//
import SpriteKit
class GlueBlockNode: BlockNode {
weak var gameScene: GameScene!
// Side that are connected
var connected: [Side : Bool] = [.up: false, .down: false, .left: false, .right: false, .centre: false]
#if DEBUG
var circles = [SKShapeNode]()
#endif
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
physicsBody?.categoryBitMask = Category.gluBlock
physicsBody?.collisionBitMask = Category.all ^ Category.tools
if physicsBody!.isDynamic {
physicsBody?.fieldBitMask = Category.fields
}
}
override func setup(scene: GameScene) {
super.setup(scene: scene)
gameScene = scene
checkConnected()
}
func checkConnected() {
for child in children {
// Modify connected array to include pre-added nodes
let side: Side
switch child.position {
case up:
connected[.up] = true
side = .up
case down:
connected[.down] = true
side = .down
case left:
connected[.left] = true
side = .left
case right:
connected[.right] = true
side = .right
case centre:
// For gravity
connected[.centre] = true
side = .centre
default:
print("Couldn't find side at \(child.position)")
continue
}
if child.name == "fanPlaceholder" && side != .centre {
// Make sure connected side is false
connected[side] = false
// Get fan node from file
let fanNode = SKNode(fileNamed: "FanRef")?.children.first as! FanNode
fanNode.removeFromParent()
if add(node: fanNode, to: side) {
// Fan setup after it has been added
fanNode.setup(scene: gameScene, block: self, side: side)
// Removes the placeholder
child.removeFromParent()
}
}
}
// Detect blocks around so as to remove the possiblity of a fan inbetween blocks
let rect = CGRect(origin: frame.origin, size: frame.size)
var transform = CGAffineTransform(translationX: 0, y: frame.height)
let pathUp = CGPath(rect: rect, transform: &transform)
let regionUp = SKRegion(path: pathUp)
transform = CGAffineTransform(translationX: 0, y: -frame.height)
let pathDown = CGPath(rect: rect, transform: &transform)
let regionDown = SKRegion(path: pathDown)
transform = CGAffineTransform(translationX: -frame.height, y: 0)
let pathLeft = CGPath(rect: rect, transform: &transform)
let regionLeft = SKRegion(path: pathLeft)
transform = CGAffineTransform(translationX: frame.height, y: 0)
let pathRight = CGPath(rect: rect, transform: &transform)
let regionRight = SKRegion(path: pathRight)
gameScene.enumerateChildNodes(withName: "//*Block") { child, _ in
if child is SKSpriteNode {
let position = self.parent!.convert(child.position, from: child.parent!)
func addBlock(to side: Side) {
self.connected[side] = true
if var breakable = child as? Breakable {
breakable.glueBlock = self
breakable.side = side
}
}
if regionUp.contains(position) {
addBlock(to: .up)
} else if regionDown.contains(position) {
addBlock(to: .down)
} else if regionLeft.contains(position) {
addBlock(to: .left)
} else if regionRight.contains(position) {
addBlock(to: .right)
}
}
}
//debugConnected()
}
func remove(for side: Side) {
connected[side] = false
//debugConnected()
}
#if DEBUG
func debugConnected() {
for circle in circles {
circle.removeFromParent()
}
for (connect, yes) in connected {
if yes {
let circle = SKShapeNode(circleOfRadius: 10)
circle.fillColor = .blue
circle.strokeColor = .blue
circle.position = connect.position
circle.zPosition = 100
circles.append(circle)
addChild(circle)
}
}
}
#endif
func getSideIfConnected(contact: SKPhysicsContact) -> Side? {
let side = super.getSide(contact: contact)
// Check if side is connected
if connected[side]! {
return nil
}
return side
}
// Add a node, based on side. Returns true if successful
func add(node: SKSpriteNode, to side: Side) -> Bool {
// Make sure there isn't already one on that side
guard connected[side] == false else {
return false
}
let position: CGPoint
let zRotation: CGFloat
switch side {
case .up:
position = up
zRotation = CGFloat(0).degreesToRadians()
case .down:
position = down
zRotation = CGFloat(180).degreesToRadians()
case .left:
position = left
zRotation = CGFloat(90).degreesToRadians()
case .right:
position = right
zRotation = CGFloat(270).degreesToRadians()
case .centre:
position = centre
zRotation = CGFloat(0).degreesToRadians()
}
connected[side] = true
if node.parent == nil {
node.position = position
node.zRotation = zRotation
addChild(node)
} else {
node.move(toParent: self)
node.run(SKAction.move(to: position, duration: 0.1)) {
// Check if the physics body is dynamic
if self.physicsBody!.isDynamic {
if let body1 = node.physicsBody,
let body2 = self.physicsBody,
let scene = self.scene,
let parent = node.parent {
node.physicsBody?.contactTestBitMask ^= Category.gluBlock
let anchor = scene.convert(node.position, from: parent)
let joint = SKPhysicsJointPin.joint(withBodyA: body1, bodyB: body2, anchor: anchor)
scene.physicsWorld.add(joint)
}
} else {
node.physicsBody?.isDynamic = false
}
}
}
if var breakable = node as? Breakable {
breakable.glueBlock = self
breakable.side = side
}
//debugConnected()
return true
}
func add(gravityNode: GravityNode) -> Bool {
// Check there are no other nodes
guard connected[.centre] == false else {
return false
}
// Precaution
gravityNode.removeFromParent()
gravityNode.position = centre
addChild(gravityNode)
connected[.centre] = true
//debugConnected()
return true
}
func update() {
print("Glue block")
}
}
| gpl-3.0 | 375793e2bdda31bf884d42c5dfc3a89f | 23.334677 | 103 | 0.666446 | 3.472382 | false | false | false | false |
DouKing/WYListView | WYListViewController/Demo/AddressViewController.swift | 1 | 6704 | //
// DetailViewController.swift
// WYListViewController
//
// Created by iosci on 2016/10/24.
// Copyright © 2016年 secoo. All rights reserved.
//
import UIKit
class AddressViewController: UIViewController {
enum AddressType: Int {
case province, city, area
}
var sectionDataSource: [String?] = [nil]
var selectedRows: [Int?] = [nil, nil, nil]
let name = "n"
let code = "c"
lazy var dataSource: NSDictionary = {
let path = Bundle.main.path(forResource: "test", ofType: "plist")
let info = NSDictionary(contentsOfFile: path!)
return info!
}()
lazy var provinces: [[String: String]] = {
let provinces = self.dataSource["provinces"]
return provinces! as! [[String : String]]
}()
lazy var cities: [String: [[String: String]]] = {
let provinces = self.dataSource["cities"]
return provinces! as! [String : [[String : String]]]
}()
lazy var areas: [String: [[String: String]]] = {
let provinces = self.dataSource["areas"]
return provinces! as! [String : [[String : String]]]
}()
var province: String?
var city: String?
var area: String?
@IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
let listVC = WYListView()
listVC.dataSource = self
listVC.delegate = self
listVC.view.frame = self.contentView.bounds
self.addChildViewController(listVC)
self.contentView.addSubview(listVC.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - WYListViewDataSource -
extension AddressViewController: WYListViewDataSource, WYListViewDelegate {
func numberOfSections(in listView: WYListView) -> Int {
return self.sectionDataSource.count
}
func listView(_ listView: WYListView, numberOfRowsInSection section: Int) -> Int {
guard let type = AddressType(rawValue: section) else {
return 0
}
switch type {
case .province:
return self.provinces.count
case .city:
guard let index = self.selectedRows[AddressType.province.rawValue] else { return 0 }
guard let code = self.provinces[index][self.code] else { return 0 }
guard let cities = self.cities[code] else { return 0 }
return cities.count
case .area:
guard let index = self.selectedRows[AddressType.province.rawValue] else { return 0 }
guard let code = self.provinces[index][self.code] else { return 0 }
guard let cities = self.cities[code] else { return 0 }
guard let idx = self.selectedRows[AddressType.city.rawValue] else { return 0 }
guard let c = cities[idx][self.code] else { return 0 }
guard let areas = self.areas[c] else { return 0 }
return areas.count
}
}
func listView(_ listView: WYListView, titleForSection section: Int) -> String? {
return self.sectionDataSource[section]
}
func listView(_ listView: WYListView, titleForRowAtIndexPath indexPath: IndexPath) -> String? {
guard let type = AddressType(rawValue: indexPath.section) else {
return nil
}
switch type {
case .province:
return self.provinces[indexPath.row][self.name]
case .city:
guard let index = self.selectedRows[AddressType.province.rawValue] else { return nil }
guard let code = self.provinces[index][self.code] else { return nil }
guard let cities = self.cities[code] else { return nil }
return cities[indexPath.row][self.name]
case .area:
guard let index = self.selectedRows[AddressType.province.rawValue] else { return nil }
guard let code = self.provinces[index][self.code] else { return nil }
guard let cities = self.cities[code] else { return nil }
guard let idx = self.selectedRows[AddressType.city.rawValue] else { return nil }
guard let c = cities[idx][self.code] else { return nil }
guard let areas = self.areas[c] else { return nil }
return areas[indexPath.row][self.name]
}
}
func listView(_ listView: WYListView, didSelectRowAtIndexPath indexPath: IndexPath) {
let row = self.selectedRows[indexPath.section]
self.selectedRows[indexPath.section] = indexPath.row
self.sectionDataSource[indexPath.section] = self.listView(listView, titleForRowAtIndexPath: indexPath)
if let selectedRow = row, selectedRow == indexPath.row {
} else {
self.selectedRows.remove(after: indexPath.section)
self.sectionDataSource.remove(after: indexPath.section)
if indexPath.section < AddressType.area.rawValue {
self.sectionDataSource.append(nil)
for _ in (indexPath.section + 1)...AddressType.area.rawValue {
self.selectedRows.append(nil)
}
}
}
var selectedIndexPaths: [IndexPath] = []
for (idx, row) in self.selectedRows.enumerated() {
if row != nil {
selectedIndexPaths.append(IndexPath(row: row!, section: idx))
}
}
listView.reloadData(selectRowsAtIndexPaths: selectedIndexPaths)
listView.scroll(to: min(indexPath.section + 1, AddressType.area.rawValue), animated: true, after: 0.3)
if let type = AddressType(rawValue: indexPath.section) {
switch type {
case .province:
self.province = self.listView(listView, titleForRowAtIndexPath: indexPath)
case .city:
self.city = self.listView(listView, titleForRowAtIndexPath: indexPath)
case .area:
self.area = self.listView(listView, titleForRowAtIndexPath: indexPath)
let address = "\(self.province) \(self.city) \(self.area)"
let alert = UIAlertController(title: address, message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
}
}
extension Array {
mutating func remove(after index: Int) {
while self.count > index + 1 {
self.removeLast()
}
}
}
| mit | 709dedb37c143424ee4bf3fa4695ed49 | 37.073864 | 110 | 0.603492 | 4.712377 | false | false | false | false |
semonchan/LearningSwift | 语法/4.Swift基础语法.playground/Contents.swift | 1 | 1847 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class Vehicle {
var numberOfWheels = 0
var description: String {
return"\(numberOfWheels)wheel(s)"
}
}
let vehicle = Vehicle()
class Bicycle: Vehicle {
override init() {
super.init()
numberOfWheels = 2
}
}
// 指定构造器和便利构造器
// 一般便利构造器是为了方便构造拥有默认值属性的实例
class Food {
var name: String
// 这个类的指定构造器
init(name: String) {
self.name = name
}
// 这个类的便利构造器
convenience init() {
self.init(name: "[Unnamed]")
}
}
class Recipelngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init (name: String) {
self.init(name: name, quantity: 1)
}
}
let x = Recipelngredient()
class ShoppingListItem: Recipelngredient {
var purchased = false
var description: String {
var output = "\(quantity)x\(name)"
output += purchased ? "✅" : "❎"
return output
}
}
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6)
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
class Bank {
static var coinslnBank = 10_000
static func distribute(coins numberOfCoinsRequested: Int) -> Int {
let numberOfCoinsToVend = min(numberOfCoinsRequested, coinslnBank)
coinslnBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receive(coins: Int) {
coinslnBank += coins
}
}
| mit | 227929a0650e1c51b0ef2944516a95bf | 18.3 | 74 | 0.624064 | 3.903371 | false | false | false | false |
MessageKit/MessageKit | Sources/Controllers/MessagesViewController+PanGesture.swift | 1 | 3317 | // MIT License
//
// Copyright (c) 2017-2022 MessageKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
extension MessagesViewController {
// MARK: Internal
/// Display time of message by swiping the cell
func addPanGesture() {
panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
guard let panGesture = panGesture else {
return
}
panGesture.delegate = self
messagesCollectionView.addGestureRecognizer(panGesture)
messagesCollectionView.clipsToBounds = false
}
func removePanGesture() {
guard let panGesture = panGesture else {
return
}
panGesture.delegate = nil
self.panGesture = nil
messagesCollectionView.removeGestureRecognizer(panGesture)
messagesCollectionView.clipsToBounds = true
}
// MARK: Private
@objc
private func handlePanGesture(_ gesture: UIPanGestureRecognizer) {
guard let parentView = gesture.view else {
return
}
switch gesture.state {
case .began, .changed:
messagesCollectionView.showsVerticalScrollIndicator = false
let translation = gesture.translation(in: view)
let minX = -(view.frame.size.width * 0.35)
let maxX: CGFloat = 0
var offsetValue = translation.x
offsetValue = max(offsetValue, minX)
offsetValue = min(offsetValue, maxX)
parentView.frame.origin.x = offsetValue
case .ended:
messagesCollectionView.showsVerticalScrollIndicator = true
UIView.animate(
withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.8,
options: .curveEaseOut,
animations: {
parentView.frame.origin.x = 0
},
completion: nil)
default:
break
}
}
}
// MARK: - MessagesViewController + UIGestureRecognizerDelegate
extension MessagesViewController: UIGestureRecognizerDelegate {
/// Check Pan Gesture Direction:
open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let panGesture = gestureRecognizer as? UIPanGestureRecognizer else {
return false
}
let velocity = panGesture.velocity(in: messagesCollectionView)
return abs(velocity.x) > abs(velocity.y)
}
}
| mit | db2869d2abfdeb2570021882af0951c9 | 33.195876 | 94 | 0.719325 | 4.950746 | false | false | false | false |
SwiftFS/Swift-FS-China | Sources/SwiftFSChina/router/Search.swift | 1 | 2609 | //
// Search.swift
// PerfectChina
//
// Created by mubin on 2017/8/10.
//
//
import Foundation
import PerfectHTTP
import PerfectLib
class Search {
static func query(data: [String:Any]) throws -> RequestHandler {
return {
request, response in
do{
guard let q = request.param(name: "q") else {
response.render(template: "search")
return
}
let page_size = page_config.index_topic_page_size
let page_no = request.param(name: "page_no")?.int ?? 1
let total_count = try SearchServer.quert_cout(query: q)
let total_page = Utils.total_page(total_count: total_count, page_size: page_size)
let result_topic = try SearchServer.query_by_topic(query:q)
let result_user = try SearchServer.query_by_user(query: q)
let user_count = result_user.count
let user_json_encoded = try? encoder.encode(result_user)
let topic_json_encoded = try? encoder.encode(result_topic)
if user_json_encoded != nil && topic_json_encoded != nil {
guard let user_json = encodeToString(data: user_json_encoded!) else{
return
}
guard let topic_json = encodeToString(data: topic_json_encoded!) else{
return
}
guard let user_json_decoded = try user_json.jsonDecode() as? [[String:Any]] else{
return
}
guard let topic_json_decoded = try topic_json.jsonDecode() as? [[String:Any]] else{
return
}
let content:[String:Any] = ["total_count":total_count + user_count
,"q":q
,"useritems":user_json_decoded
,"topicitems":topic_json_decoded]
response.render(template: "search/search", context: content)
}
}catch{
Log.error(message: "\(error)")
}
}
}
}
private extension String {
func positionOf(sub:String)->Int {
var pos = -1
if let range = range(of:sub) {
if !range.isEmpty {
pos = characters.distance(from:startIndex, to:range.lowerBound)
}
}
return pos
}
}
| mit | 14341b3190d6b4bf5b9f1e26ad289924 | 32.883117 | 103 | 0.477194 | 4.642349 | false | false | false | false |
Glucosio/glucosio-ios | glucosio/Classes/Watch/Timeline.swift | 2 | 3151 | import Foundation
public class TimelineItem : NSObject /*, Equatable */ {
public var timestamp : Date
public var value: String
public var unit: String
public var desc : String
@objc public init(date: Date, value: String, unit: String, description: String) {
timestamp = date
self.value = value
self.unit = unit
desc = description
}
@objc public override var description: String {
return "TimelineItem: \(timestamp) \(value) \(unit) \(desc)"
}
// MARK: Equality
static func == (lhs: TimelineItem, rhs: TimelineItem) -> Bool {
return lhs.timestamp == rhs.timestamp &&
lhs.value == rhs.value &&
lhs.unit == rhs.unit &&
lhs.description == rhs.description
}
// MARK: Dictionary (de)serialization
@objc convenience init(d: Dictionary<String, String>) {
//TODO: how to use reflection here?
self.init(date: Date(timeIntervalSince1970 : Double(d["timestamp"] ?? "") ?? 0.0),
value: d["value"] ?? "",
unit: d["unit"] ?? "",
description: d["desc"] ?? "")
}
public func toDictionary() -> Dictionary<String, String> {
var d = Dictionary<String, String>.init()
let mirror = Mirror(reflecting: self)
for (name, value) in mirror.children {
guard let name = name else { continue }
if(value is Date) {
d[name] = String(describing: (value as! Date).timeIntervalSince1970)
} else {
d[name]=value as? String
}
}
return d
}
}
public class DayTimeline : NSObject /*, Equatable */ {
public var elements : Array<TimelineItem>
@objc public init(items : Array<TimelineItem>) {
elements = items
// print(elements)
}
// MARK: UserDefaults (de)serialization
public convenience override init() {
self.init(UserDefaults.init())
}
public convenience init(_ def: UserDefaults) {
self.init(def, key: "timeline")
}
public convenience init(_ def: UserDefaults, key: String) {
self.init(d: def.dictionary(forKey: key) ?? Dictionary.init())
}
public func toUserDefaults(_ def : UserDefaults) {
toUserDefaults(def, key: "timeline")
}
public func toUserDefaults(_ def : UserDefaults, key: String) {
def.setValue(toDictionary(), forKey: key);
}
// MARK: Dictionary (de)serialization
public convenience init(d: Dictionary<String, Any>) {
if let rawElements = d["elements"] {
let elements = (rawElements as! Array<Dictionary>).map { d in TimelineItem.init(d: d) }
self.init(items: elements)
} else {
self.init(items: [])
}
}
//d[elements] = Array[Dictionary<String,String>]
@objc public func toDictionary() -> Dictionary<String, Array<Dictionary<String, String>>> {
var d = Dictionary<String, Array<Dictionary<String, String>>>.init()
d["elements"] = elements.map { t in t.toDictionary() }
return d
}
}
| gpl-3.0 | 36a2cb968b6c6384358d357ade345eea | 29.009524 | 99 | 0.578546 | 4.35823 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK | Evrythng-iOS/ScopeResource.swift | 1 | 848 | //
// ScopeResource.swift
// EvrythngiOS
//
// Created by JD Castro on 22/05/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import UIKit
import Moya_SwiftyJSONMapper
import SwiftyJSON
open class ScopeResource {
var users: Array<String>?
var projects: Array<String>?
var jsonData: JSON? = nil
public init() {
}
required public init?(jsonData:JSON){
self.jsonData = jsonData
self.users = jsonData["allU"].arrayObject as? [String]
self.projects = jsonData["allP"].arrayObject as? [String]
}
public class func toString() -> NSString? {
let data = try! JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
return string
}
}
| apache-2.0 | 8f6b62599487cfe8d2f772cb1af33230 | 22.527778 | 93 | 0.637544 | 4.11165 | false | false | false | false |
6ag/AppScreenshots | AppScreenshots/Classes/Module/Home/View/JFPhotoCollectionViewCell.swift | 1 | 6635 | //
// JFPhotoCollectionViewCell.swift
// AppScreenshots
//
// Created by zhoujianfeng on 2017/2/4.
// Copyright © 2017年 zhoujianfeng. All rights reserved.
//
import UIKit
class JFPhotoCollectionViewCell: UICollectionViewCell {
var materialParameter: JFMaterialParameter? {
didSet {
guard let materialParameter = materialParameter else { return }
// 模板图片
imageView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.sourceImageName ?? "", ofType: nil) ?? "")
// 配图
accessoryView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.accessoryImageName ?? "", ofType: nil) ?? "")
// 遮罩
coverView.image = UIImage(contentsOfFile: Bundle.main.path(forResource: materialParameter.coverImageName ?? "", ofType: nil) ?? "")
// 是否正在编辑
selectedIconView.isHidden = !materialParameter.isSelected
// 应用截图
screenShotImageView.image = materialParameter.screenShotImage
// 标题
titleLabel.text = materialParameter.title
titleLabel.font = UIFont(name: "PingFangSC-Semibold", size: SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.titleFontSize))
titleLabel.textColor = UIColor.colorWithHexString(materialParameter.titleTextColorHex ?? "")
// 副标题
subtitleLabel.text = materialParameter.subtitle
subtitleLabel.font = UIFont(name: "PingFangSC-Semibold", size: SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.subtitleFontSize))
subtitleLabel.textColor = UIColor.colorWithHexString(materialParameter.subtitleTextColorHex ?? "")
titleLabel.snp.updateConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.titleY))
}
subtitleLabel.snp.updateConstraints { (make) in
make.centerX.equalTo(contentView)
make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.subtitleY))
}
screenShotImageView.snp.updateConstraints { (make) in
make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.screenShotX))
make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.screenShotY))
make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.screenShotWidth))
make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.screenShotHeight))
}
accessoryView.snp.updateConstraints { (make) in
make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.accessoryX))
make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.accessoryY))
make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.accessoryWidth))
make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.accessoryHeight))
}
coverView.snp.updateConstraints { (make) in
make.left.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.coverX))
make.top.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.coverY))
make.width.equalTo(SettingPhotoItemWidth / SCREEN_WIDTH * layoutHorizontal(iPhone6: materialParameter.coverWidth))
make.height.equalTo(SettingPhotoItemHeight / SCREEN_HEIGHT * layoutVerticalX(iPhone6: materialParameter.coverHeight))
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - 懒加载
/// 展示图
fileprivate lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = layoutHorizontal(iPhone6: 2)
imageView.layer.masksToBounds = true
return imageView
}()
/// 选中图标
lazy var selectedIconView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "img_select"))
return imageView
}()
/// 标题
fileprivate lazy var titleLabel: UILabel = {
let label = UILabel()
return label
}()
/// 副标题
fileprivate lazy var subtitleLabel: UILabel = {
let label = UILabel()
return label
}()
/// 上传的屏幕截图
fileprivate lazy var screenShotImageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
/// 配图
fileprivate lazy var accessoryView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
/// 遮罩
fileprivate lazy var coverView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
}
// MARK: - 设置界面
extension JFPhotoCollectionViewCell {
fileprivate func prepareUI() {
contentView.addSubview(imageView)
contentView.addSubview(selectedIconView)
contentView.addSubview(titleLabel)
contentView.addSubview(subtitleLabel)
contentView.addSubview(screenShotImageView)
contentView.addSubview(coverView)
contentView.addSubview(accessoryView)
imageView.snp.makeConstraints { (make) in
make.edges.equalTo(self.contentView)
}
selectedIconView.snp.makeConstraints { (make) in
make.top.equalTo(layoutVerticalX(iPhone6: -5))
make.size.equalTo(CGSize(
width: layoutHorizontal(iPhone6: 15),
height: layoutVerticalX(iPhone6: 15)))
make.right.equalTo(layoutHorizontal(iPhone6: 5))
}
}
}
| mit | a1e0ec1d24d3e3fa54d7dea91887ae26 | 40.044025 | 177 | 0.64266 | 5.175258 | false | false | false | false |
xuzhou524/Convenient-Swift | Controller/HomeViewController.swift | 1 | 12878 | //
// HomeViewController.swift
// Convenient-Swift
//
// Created by gozap on 16/3/2.
// Copyright © 2016年 xuzhou. All rights reserved.
//
import UIKit
import Alamofire
import SnapKit
import KVOController
import ObjectMapper
import AlamofireObjectMapper
import TMCache
import SVProgressHUD
let kTMCacheWeatherArray = "kTMCacheWeatherArray"
typealias cityHomeViewbackfunc=(_ weatherModel:WeatherModel)->Void
class HomeViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var HomeWeatherMdoel = WeatherModel()
var requCityName = XZClient.sharedInstance.username!
var weatherArray = NSMutableArray()
var weatherlocalArray = NSMutableArray()
//var alamofireManager : Manager?
var xxWeiHaoArray = NSMutableArray()
var cityNameButton : UIButton?
var cityIconImageView : UIImageView?
fileprivate var _tableView : UITableView!
fileprivate var tableView :UITableView{
get{
if _tableView == nil{
_tableView = UITableView()
_tableView.backgroundColor = XZSwiftColor.convenientBackgroundColor
_tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
_tableView.delegate = self
_tableView.dataSource = self
self.tableView.register(Weather_titleTabeleViewCell.self, forCellReuseIdentifier: "Weather_titleTabeleViewCell")
self.tableView.register(WeatherTabeleViewCell.self, forCellReuseIdentifier: "WeatherTabeleViewCell")
self.tableView.register(Weather_LineTabeleViewCell.self, forCellReuseIdentifier: "Weather_LineTabeleViewCell")
self.tableView.register(Weather_TimeTabeleViewCell.self, forCellReuseIdentifier: "Weather_TimeTabeleViewCell")
self.tableView.register(Weather_WeekTabeleViewCell.self, forCellReuseIdentifier: "Weather_WeekTabeleViewCell")
}
return _tableView
}
}
override func viewDidLoad() {
super.viewDidLoad()
cityNameButton = UIButton()
cityNameButton!.setImage(UIImage(named: ""), for: UIControl.State())
cityNameButton!.adjustsImageWhenHighlighted = false
if (HomeWeatherMdoel.life == nil) {
cityNameButton!.setTitle(XZClient.sharedInstance.username!, for: UIControl.State())
}else{
cityNameButton!.setTitle(HomeWeatherMdoel.realtime!.city_name! as String, for: UIControl.State())
}
cityNameButton!.addTarget(self, action: #selector(HomeViewController.cityClick), for: .touchUpInside)
cityIconImageView = UIImageView()
cityIconImageView?.isUserInteractionEnabled = true
cityIconImageView?.image = UIImage.init(named: "fujindizhi")
cityNameButton!.addSubview(cityIconImageView!)
cityIconImageView?.snp.makeConstraints({ (make) in
make.centerY.equalTo(cityNameButton!);
make.right.equalTo(cityNameButton!.snp.left).offset(-5)
make.width.height.equalTo(28)
});
self.navigationItem.titleView = cityNameButton
self.view.addSubview(self.tableView);
self.tableView.snp.makeConstraints{ (make) -> Void in
make.top.right.bottom.left.equalTo(self.view);
}
let leftButton = UIButton()
leftButton.frame = CGRect(x: 0, y: 0, width: 35, height: 30)
leftButton.imageEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
leftButton.setImage(UIImage(named: "bank"), for: UIControl.State())
leftButton.adjustsImageWhenHighlighted = false
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
leftButton.addTarget(self, action: #selector(leftClick), for: .touchUpInside)
if (self.HomeWeatherMdoel.life == nil) {
self.requCityName = XZClient.sharedInstance.username!
}else{
self.requCityName = self.HomeWeatherMdoel.realtime?.city_name ?? ""
}
self.cityNameButton?.setTitle(self.requCityName, for: UIControl.State())
self.asyncRequestData()
if TMCache.shared().object(forKey: kTMCacheWeatherArray) != nil{
self.weatherlocalArray = TMCache.shared().object(forKey: kTMCacheWeatherArray) as! NSMutableArray
}
if self.weatherlocalArray.count > 0 {
self.HomeWeatherMdoel = self.weatherlocalArray[0] as! WeatherModel
}
}
@objc func leftClick(){
self.dismiss(animated: true, completion: nil)
}
@objc func cityClick(){
let cityVC = CityViewController()
// cityVC.cityViewBack { (weatherModel) -> Void in
// self.HomeWeatherMdoel = weatherModel
// self.requCityName = weatherModel.realtime!.city_name! as String
// self.cityNameButton!.setTitle(self.HomeWeatherMdoel.realtime!.city_name! as String, for: UIControlState())
// self.asyncRequestData()
// self.myHomeFunc!(weatherModel: weatherModel);
// }
self.navigationController?.pushViewController(cityVC, animated: true)
}
func asyncRequestData() -> Void{
//根据城市名称 获取城市ID
//http://apistore.baidu.com/microservice/cityinfo?cityname=北京
//得到ID 获取天气图标对应的值
//http://tq.91.com/api/?act=210&city=101180712&sv=3.15.3
//搜索城市
//http://zhwnlapi.etouch.cn/Ecalender/api/city?keyword=%E6%B8%85%E8%BF%9C×pan=1457518656.715996&type=search
//获取天气信息
let urlString = "https://op.juhe.cn/onebox/weather/query"
let prames = [
"cityname" : self.requCityName,
"key" : "af34bbdd7948b379a0d218fc2c59c8ba"
]
AF.request(urlString, method: .post, parameters: prames, encoder: URLEncodedFormParameterEncoder.default, headers: nil, interceptor: nil).responseJSON { (response) in
if response.error == nil {
if let dict = response.value as? NSDictionary {
if let dicts = dict["result"] as? NSDictionary {
if let dictss = dicts["data"] as? NSDictionary {
if let model = WeatherModel.init(JSON: dictss as! [String : Any]) {
print(model);
self.HomeWeatherMdoel = model
if (TMCache.shared().object(forKey: kTMCacheWeatherArray) != nil){
self.weatherArray = TMCache.shared().object(forKey: kTMCacheWeatherArray) as! NSMutableArray
}
//去重
var tempBool = true
for i in 0 ..< self.weatherArray.count {
let model = self.weatherArray[i] as! WeatherModel
if model.realtime?.city_code == self.HomeWeatherMdoel.realtime?.city_code || model.realtime?.city_name == self.HomeWeatherMdoel.realtime?.city_name{
self.weatherArray.removeObject(at: i)
self.weatherArray.insert(self.HomeWeatherMdoel, at: i)
tempBool = false
break
}
}
if tempBool{
self.weatherArray.add(self.HomeWeatherMdoel)
}
// TMCache.shared().setObject(self.weatherArray, forKey: kTMCacheWeatherArray)
let date = Date()
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "MM-dd HH:mm"
let strNowTime = timeFormatter.string(from: date) as String
XZSetting.sharedInstance[KweatherTefurbishTime] = strNowTime;
var listData: NSDictionary = NSDictionary()
let filePath = Bundle.main.path(forResource: "TailRestrictions.plist", ofType:nil )
listData = NSDictionary(contentsOfFile: filePath!)!
let cityId = listData.object(forKey: self.requCityName) as? String
if (cityId != nil) {
self.asyncRequestXianXingData(cityId!)
}else{
self.tableView.reloadData()
}
}
}
}
}
}
}
}
func asyncRequestXianXingData(_ string:String) -> Void{
let urlString = "http://forecast.sina.cn/app/lifedex/v3/html/channel.php?"
let prames = [
"ch_id" : "3",
"citycode" : string,
"pt" : "3010"
]
AF.request(urlString, method: .get, parameters: prames).responseString {response in
switch response.result {
case .success:
debugPrint(response.result)
let dataImage = response.value?.data(using: String.Encoding.utf8)
let xpathParser = type(of: TFHpple()).init(htmlData: dataImage)
let elements = xpathParser?.search(withXPathQuery: "//html//body//div//div//div//div[@class='number']")
if (elements?.count)! > 0{
let temp = elements?.first as! TFHppleElement
for i in 0 ..< self.weatherArray.count {
let model = self.weatherArray[i] as! WeatherModel
if (model.realtime?.city_code == self.HomeWeatherMdoel.realtime?.city_code){
self.weatherArray.removeObject(at: i)
self.HomeWeatherMdoel.xxweihao = temp.content
self.weatherArray.insert(self.HomeWeatherMdoel, at: i)
// TMCache.shared().setObject(self.weatherArray, forKey: kTMCacheWeatherArray)
}
}
}
self.tableView .reloadData()
break
case .failure(let error):
debugPrint(error)
break
}
self.tableView .reloadData()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.HomeWeatherMdoel.life) != nil {
return 5
}
return 0
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return [40,320,35,120,35][(indexPath as NSIndexPath).row]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let titleCell = getCell(tableView, cell: Weather_titleTabeleViewCell.self, indexPath: indexPath)
titleCell.bind(self.HomeWeatherMdoel)
titleCell.selectionStyle = .none
return titleCell
}else if indexPath.row == 1 {
let weatherCell = getCell(tableView, cell: WeatherTabeleViewCell.self, indexPath: indexPath)
weatherCell.selectionStyle = .none
weatherCell.bind(self.HomeWeatherMdoel)
return weatherCell
}else if indexPath.row == 2 {
let weatherTimeCell = getCell(tableView, cell: Weather_TimeTabeleViewCell.self, indexPath: indexPath)
weatherTimeCell.selectionStyle = .none
weatherTimeCell.bind(self.HomeWeatherMdoel)
return weatherTimeCell
}
else if (indexPath as NSIndexPath).row == 3{
let lineCell = getCell(tableView, cell: Weather_LineTabeleViewCell.self, indexPath: indexPath)
lineCell.selectionStyle = .none
if let array = self.HomeWeatherMdoel.weather {
lineCell.weakWeatherArray = array
lineCell.configUI()
}
lineCell.backgroundColor = UIColor.white
return lineCell
}
else if (indexPath as NSIndexPath).row == 4{
let weekTimeCell = getCell(tableView, cell: Weather_WeekTabeleViewCell.self, indexPath: indexPath)
weekTimeCell.selectionStyle = .none
weekTimeCell.binde(self.HomeWeatherMdoel)
return weekTimeCell
}
return UITableViewCell()
}
}
| mit | 7e0eede4fcd2a01ea0bf7c1e0623727e | 44.400709 | 184 | 0.578849 | 4.813158 | false | false | false | false |
SoneeJohn/WWDC | WWDC/AppCoordinator+UserActivity.swift | 1 | 724 | //
// AppCoordinator+UserActivity.swift
// WWDC
//
// Created by Guilherme Rambo on 06/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
import RxSwift
import ConfCore
import PlayerUI
extension AppCoordinator {
func updateCurrentActivity(with item: UserActivityRepresentable?) {
guard let item = item else {
currentActivity?.invalidate()
currentActivity = nil
return
}
let activity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
activity.title = item.title
activity.webpageURL = item.webUrl
activity.becomeCurrent()
currentActivity = activity
}
}
| bsd-2-clause | f4815f15e1d2a242609bea985a486414 | 20.264706 | 82 | 0.674965 | 5.164286 | false | false | false | false |
joshdholtz/Few.swift | Few-iOS/Image.swift | 1 | 1337 | //
// Image.swift
// Few
//
// Created by Coen Wessels on 13-03-15.
// Copyright (c) 2015 Josh Abernathy. All rights reserved.
//
import UIKit
public class Image: Element {
public var image: UIImage?
public var scaling: UIViewContentMode
public var clipsToBounds: Bool
public init(_ image: UIImage?, scaling: UIViewContentMode = .ScaleAspectFit, clipsToBounds: Bool = false) {
self.image = image
self.scaling = scaling
self.clipsToBounds = clipsToBounds
let size = image?.size ?? CGSize(width: Node.Undefined, height: Node.Undefined)
super.init(frame: CGRect(origin: CGPointZero, size: size))
}
// MARK: Element
public override func applyDiff(old: Element, realizedSelf: RealizedElement?) {
super.applyDiff(old, realizedSelf: realizedSelf)
if let view = realizedSelf?.view as? UIImageView {
if view.contentMode != scaling {
view.contentMode = scaling
}
if view.image != image {
view.image = image
realizedSelf?.markNeedsLayout()
}
if view.clipsToBounds != clipsToBounds {
view.clipsToBounds = clipsToBounds
}
}
}
public override func createView() -> ViewType {
let view = UIImageView(frame: frame)
view.alpha = alpha
view.hidden = hidden
view.image = image
view.contentMode = scaling
view.clipsToBounds = clipsToBounds
return view
}
}
| mit | 0dea09cd26310c1f31646a71efdd86c0 | 23.309091 | 108 | 0.700075 | 3.724234 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | UIApplication/UIApplication/ViewController.swift | 1 | 1496 | //
// ViewController.swift
// UIApplication
//
// Created by bingoogol on 14/9/6.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
println("viewDidLoad")
}
@IBAction func clickMe() {
// 一般来讲,所有shared开头创建的对象,都是单例
var app = UIApplication.sharedApplication()
// 设置图标右上角显示的数字
// 提醒:在设置数字时,要谨慎,对于强迫症患者
//app.applicationIconBadgeNumber = 10
// 显示联网状态的提示,一般有网络请求,会自动显示
//app.networkActivityIndicatorVisible = true
//在iOS中,很多东西都可以通过URL来访问,例如:电话、短信、电子邮件等
//var url = NSURL(string: "http://www.baidu.com")
// 电话会直接呼出
//var url = NSURL(string: "tel://10086")
// 会跳出短信发送界面,等待用户编辑并发送短信
//var url = NSURL(string: "sms://10086")
//app.openURL(url)
// 阻止屏幕变暗,慎重使用,缺省为false
app.idleTimerDisabled = true
}
// 当应用程序出现内存警告时,控制器可以在此方法中释放自己的资源
override func didReceiveMemoryWarning() {
}
} | apache-2.0 | c2b80eb2950fcbb8ef322e35e19ca293 | 24.311111 | 57 | 0.577329 | 3.545171 | false | false | false | false |
ColinConduff/BlocFit | BlocFit/Supporting Files/Supporting Models/BFFormatter.swift | 1 | 1261 | //
// BFFormatter.swift
// BlocFit
//
// Created by Colin Conduff on 11/9/16.
// Copyright © 2016 Colin Conduff. All rights reserved.
//
import Foundation
struct BFFormatter {
static let numberFormatter = NumberFormatter()
static let dateFormatter = DateFormatter()
static let dateIntervalFormatter = DateIntervalFormatter()
static func stringFrom(number: Double, maxDigits: Int = 2) -> String {
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = maxDigits
numberFormatter.roundingMode = .up
return numberFormatter.string(from: (number as NSNumber))!
}
static func stringFrom(totalSeconds: Double) -> String {
let time = BFUnitConverter.hoursMinutesAndSecondsFrom(totalSeconds: totalSeconds)
let hours = Int(time.hours)
let minutes = Int(time.minutes)
let seconds = Int(time.seconds)
if totalSeconds >= 3600 {
return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
} else if minutes > 9 {
return String(format: "%02i:%02i", minutes, seconds)
} else {
return String(format: "%0i:%02i", minutes, seconds)
}
}
}
| mit | dcc14d6e00d63f80fe064aaf4161fb5c | 29.731707 | 89 | 0.63254 | 4.59854 | false | false | false | false |
PhillipEnglish/TIY-Assignments | Forecaster/Forecaster/ModalZipCodeViewController.swift | 1 | 5596 | //
// ModalZipCodeViewController.swift
// Forecaster
//
// Created by Phillip English on 10/30/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreLocation
class ModalZipCodeViewController: UIViewController, UITextFieldDelegate, CLLocationManagerDelegate
{
@IBOutlet weak var zipCodeTextfield: UITextField!
// @IBOutlet weak var currentLocationButton: UIButton!
let locationManager = CLLocationManager()
let geocoder = CLGeocoder()
var delegate: modalZipCodeViewControllerDelegate?
var location: String = ""
var zipCode: String = ""
var cities = [City]()
override func viewDidLoad()
{
super.viewDidLoad()
//currentLocationButton.enabled = false
configureLocationManager()
navigationController?.navigationBar.barTintColor = UIColor.purpleColor()
zipCodeTextfield.becomeFirstResponder()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: -UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
var rc = false
if zipCodeTextfield.text != ""
{
if validateZipCode(textField.text!)
{
zipCode = textField.text!
textField.resignFirstResponder()
rc = true
delegate?.zipCodeWasChosen(Int(zipCode)!)
}
else
{
textField.text = ""
textField.becomeFirstResponder()
}
}
return rc
}
func validateZipCode(zip: String) -> Bool
{
let characterSet = NSCharacterSet(charactersInString: "0123456789")
if zip.characters.count == 5 && zip.rangeOfCharacterFromSet(characterSet)?.count == 1
{
return true
}
else
{
return false
}
}
func configureLocationManager()
{
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted
{
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined
{
locationManager.requestWhenInUseAuthorization()
}
else
{
//currentLocationButton.enabled = true
}
}
}
@IBAction func findCity(sender: UIButton)
{
if validateZipCode(zipCodeTextfield.text!)
{
search(Int(zipCodeTextfield.text!)!)
}
}
func search(zip: Int)
{
delegate?.zipCodeWasChosen(zip)
self.dismissViewControllerAnimated(true, completion: nil)
}
// func search(zip: String)
// {
// delegate?.zipCodeWasChosen(zip)
// }
// func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus)
// {
// currentLocationButton.enabled = true
// }
//
// func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
// {
// print(error.localizedDescription)
// }
//
// func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) //location array orders locations as they are updated
// {
// let location = locations.last
// geocoder.reverseGeocodeLocation(location!, completionHandler: {(placemark: [CLPlacemark]?, error: NSError?) -> Void in
//
// if error != nil
// {
// print(error?.localizedDescription)
// }
// else
// {
// self.locationManager.stopUpdatingLocation()
// let cityName = placemark?[0].locality
// let zipCode = placemark?[0].postalCode
// //self.locationTextField.text = zipCode!
// let lat = location?.coordinate.latitude
// let lng = location?.coordinate.longitude
// //let aCity = City(cityName: cityName!, lat: lat!, long: lng!)
// //self.delegate?.cityWasFound(aCity) // here the delegate is in the main tableview controller
// }
// }
//MARK: - Action Handlers
// @IBAction func addCity(sender: UIButton)
// {
// search(zipCodeTextfield.text!)
// self.dismissViewControllerAnimated(true, completion: nil)
// }
//
// @IBAction func useLocationTapped(sender: UIButton)
// {
// locationManager.startUpdatingLocation() //asks gps chip where the user is and updates the location
// }
// MARK: - CLLocation related methods
// func configureLocationManager()
// {
// if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Denied && CLLocationManager.authorizationStatus() != CLAuthorizationStatus.Restricted
// {
// locationManager.delegate = self
// locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.NotDetermined
// {
// locationManager.requestWhenInUseAuthorization()
// }
// else
// {
// //currentLocationButton.enabled = true
// }
// }
// }
}
| cc0-1.0 | 0caa0cde63be28e4f87cb9b1391e5a69 | 29.57377 | 163 | 0.594638 | 5.442607 | false | false | false | false |
Vaseltior/SFCore | SFCore/sources/_extensions/Int+SFBoundi.swift | 1 | 1607 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Samuel GRAU
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
// SFCore : Int+SFBoundi.swift
//
// Created by Samuel Grau on 02/03/2015.
// Copyright (c) 2015 Samuel Grau. All rights reserved.
//
import Foundation
extension Int {
public static func boundi(value: Int, min: Int, max: Int) -> Int {
var iMax = max
if (max < min) {
iMax = min
}
var bounded = value
if (bounded > iMax) {
bounded = iMax
}
if (bounded < min) {
bounded = min
}
return bounded
}
}
| mit | cd6dd68dbdc0170e9e203712454a158a | 30.509804 | 81 | 0.703174 | 4.068354 | false | false | false | false |
KoheiKanagu/hogehoge | EndTermExamAdder/EndTermExamAdder/ViewController.swift | 1 | 7589 | //
// ViewController.swift
// EndTermExamAdder
//
// Created by Kohei on 2014/12/09.
// Copyright (c) 2014年 KoheiKanagu. All rights reserved.
//
import Cocoa
import EventKit
class ViewController: NSViewController {
@IBOutlet var myTextField: NSTextField?
@IBOutlet var myComboBox: NSComboBox?
let eventStore = EKEventStore()
var calEventList: NSArray?
override func viewDidLoad() {
super.viewDidLoad()
calEventList = eventStore.calendarsForEntityType(EKEntityTypeEvent)
for var i=0; i<calEventList?.count; i++ {
myComboBox?.insertItemWithObjectValue((calEventList![i] as EKCalendar).title, atIndex: (myComboBox?.numberOfItems)!)
}
}
@IBAction func addButtonAction(sender: AnyObject) {
if myComboBox?.indexOfSelectedItem == -1 {
println("ComboBox未選択")
return
}
let contents = loadHTML((myTextField?.stringValue)!)
if contents == nil {
println("HTMLが見つかりません")
return
}
let year = (formalWithRule("<td align=\"right\" width=\"...\"><b>(.*)</b></td>", content: contents! as NSString)!)[0] as NSString
let subjects = formalWithRule("<tr bgcolor=\"#FFFFFF\">\\n(.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n.*\\n).*\"center\">", content: contents!)!
for string in subjects{
let dateAndTimeRaw = formalWithRule("<td width=\"200\" align=\"center\">(.*)</td>", content: string as NSString)
let dateAndTime = (dateAndTimeRaw![0] as NSString).componentsSeparatedByString("/")
let date = dateAndTime[0] as NSString
let time = dateAndTime[1] as NSString
let name = (formalWithRule("<td name=\"rsunam_r\" width=\"286\">(.*)</td>", content: string as NSString)!)[0] as NSString
let clas = (formalWithRule("<td name=\"clas\" align=\"center\" >(.*)</td>", content: string as NSString)!)[0] as NSString
let teacher = (formalWithRule("<td name=\"kyoin\" width=\"162\">(.*)<br></td>", content: string as NSString)!)[0] as NSString
let convertedDate = convertDate(rawYearString: year, rawDateString: date, rawTimeString: time)
makeCalender(eventStore,
title: name + clas,
startDate: convertedDate.startTime,
endDate: convertedDate.endTime,
calendar: calEventList![myComboBox!.indexOfSelectedItem] as EKCalendar,
notes: teacher)
}
}
func convertDate(#rawYearString: NSString, rawDateString: NSString, rawTimeString: NSString) -> (startTime: NSDate, endTime: NSDate) {
let calender = NSCalendar.currentCalendar()
let components = NSDateComponents()
let year = convertYear(rawYearString)
components.year = year
let array = rawDateString.componentsSeparatedByString("(")
let array2 = (array[0] as NSString).componentsSeparatedByString("/")
components.month = (array2[0] as NSString).integerValue
components.day = (array2[1] as NSString).integerValue
var convertedTime = convertTime(rawTimeString)
components.hour = convertedTime.startTime!.hour
components.minute = convertedTime.startTime!.minute
let startTime = calender.dateFromComponents(components)
components.hour = convertedTime.endTime!.hour
components.minute = convertedTime.endTime!.minute
let endTime = calender.dateFromComponents(components)
return (startTime!, endTime!)
}
func convertYear(yearRawString: NSString) -> (Int) {
let array = yearRawString.componentsSeparatedByString("&")
var year: Int = ((array[0] as NSString).stringByReplacingOccurrencesOfString("年度", withString: "") as NSString).integerValue
if (array[1] as NSString).hasSuffix("後期") {
year++
}
return year
}
func convertTime(rawTimeString: NSString) -> (startTime: NSDateComponents?, endTime: NSDateComponents?) {
switch rawTimeString {
case "1時限":
return (makeNSDateComponents(hour: 9, minute: 30), makeNSDateComponents(hour: 10, minute: 30))
case "2時限":
return (makeNSDateComponents(hour: 11, minute: 00), makeNSDateComponents(hour: 12, minute: 00))
case "3時限":
return (makeNSDateComponents(hour: 13, minute: 30), makeNSDateComponents(hour: 14, minute: 30))
case "4時限":
return (makeNSDateComponents(hour: 15, minute: 00), makeNSDateComponents(hour: 16, minute: 00))
case "5時限":
return (makeNSDateComponents(hour: 16, minute: 30), makeNSDateComponents(hour: 17, minute: 30))
case "6時限":
return (makeNSDateComponents(hour: 18, minute: 30), makeNSDateComponents(hour: 19, minute: 30))
case "7時限":
return (makeNSDateComponents(hour: 20, minute: 00), makeNSDateComponents(hour: 21, minute: 00))
default:
return (nil, nil)
}
}
func makeNSDateComponents(#hour: Int, minute: Int) -> (NSDateComponents) {
let components = NSDateComponents()
components.hour = hour
components.minute = minute
return components
}
func loadHTML(pathString: NSString) -> (NSString?) {
if pathString.length == 0 {
return nil
}
let url: NSURL = NSURL(fileURLWithPath: pathString)!
let contents = NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: nil)
return contents
}
func formalWithRule(rule:NSString, content:NSString) -> (NSArray?) {
var resultArray = [NSString]()
var error:NSError?
let regex = NSRegularExpression(pattern: rule, options: NSRegularExpressionOptions.CaseInsensitive, error: &error);
if error != nil {
return nil
}
var matches = (regex?.matchesInString(content, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, content.length))) as Array<NSTextCheckingResult>
for match:NSTextCheckingResult in matches {
resultArray.append(content.substringWithRange(match.rangeAtIndex(1)))
}
return resultArray
}
func makeCalender(eventStore: EKEventStore, title: NSString, startDate: NSDate, endDate: NSDate, calendar: EKCalendar, notes: NSString) {
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted, error) -> Void in
if !granted {
println("カレンダーにアクセスできません")
println("セキュリティとプライバシーからカレンダーへのアクセスを許可してください")
return
}
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.calendar = calendar
event.notes = notes
var error: NSErrorPointer = nil
if eventStore.saveEvent(event, span: EKSpanThisEvent, commit: true, error: error) {
NSLog("%@に%@を%@から%@までの予定として追加しました", calendar.title, title, startDate, endDate)
}else{
println("\(title)を追加できませんでした.")
}
})
}
}
| mit | 8f5b1c4548e5f8bdc6a9a8f6048e70fd | 41.258621 | 168 | 0.614035 | 4.653797 | false | false | false | false |
whereuat/whereuat-ios | whereuat-ios/Views/RegisterView/RegisterViewController.swift | 1 | 7722 | //
// RegisterViewController.swift
// whereuat-ios
//
// Created by Raymond Jacobson on 3/1/16.
// Copyright © 2016 whereu@. All rights reserved.
//
import UIKit
import Alamofire
import SlideMenuControllerSwift
class RegisterViewController: UIViewController, RegisterViewDelegate, UITextFieldDelegate {
var verificationRequested = false
var registerView: RegisterView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.registerView = RegisterView()
self.registerView.delegate = self
view.addSubview(self.registerView)
registerForKeyboardNotifications()
self.registerView.areaCodeView.delegate = self
self.registerView.lineNumberView.delegate = self
self.registerView.verificationCodeView.delegate = self
}
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RegisterViewController.keyboardWillBeShown(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RegisterViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillBeShown(aNotification: NSNotification) {
let frame = (aNotification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
UIView.animateWithDuration(0.25, animations: {
self.registerView.frame.origin.y = -(frame.height-20)
}, completion: {
(value: Bool) in
})
}
func keyboardWillBeHidden(aNotification: NSNotification) {
self.registerView.frame.origin.y = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
* goButtonClickHandler handles clicks on the registration view.
* since the same button is used for submitting phone number as well as submitting verification code,
* there are two code paths to take.
*/
func goButtonClickHandler() {
// Fade the button out and disable it
UIView.animateWithDuration(1.0) {
self.registerView.goButton.alpha = 0.3
self.registerView.goButton.backgroundColor = ColorWheel.darkGray
self.registerView.goButton.enabled = false
}
if (self.verificationRequested) {
// We have sent a phone number to the server already and are now sending a verification code
self.sendVerificationCode()
} else {
// We are submitting a phone number
self.sendPhoneNumber()
}
}
/*
* sendVerificationCode sends a verification code to the server to get validated
*/
func sendVerificationCode() {
let verificationCode = String(self.registerView.verificationCodeView.text!)
let phoneNumber = NSUserDefaults.standardUserDefaults().stringForKey("phoneNumber")!
let gcmToken = NSUserDefaults.standardUserDefaults().stringForKey("gcmToken")!
let verificationParameters = [
"phone-#" : phoneNumber,
"gcm-token" : gcmToken,
"verification-code" : verificationCode,
"client-os" : "IOS"
]
Alamofire.request(.POST, Global.serverURL + "/account/new", parameters: verificationParameters, encoding: .JSON)
.validate()
.responseString { response in
switch response.result {
case .Success:
debugPrint(response)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isRegistered")
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
// Instantiate view controllers for main views
let contactsViewController = storyBoard.instantiateViewControllerWithIdentifier("ContactsViewController") as! ContactsViewController
let drawerViewController = storyBoard.instantiateViewControllerWithIdentifier("DrawerViewController") as! DrawerViewController
// Instantiate navigation bar view, which wraps the contactsView
let nvc: UINavigationController = UINavigationController(rootViewController: contactsViewController)
drawerViewController.homeViewController = nvc
// Instantiate the slide menu, which wraps the navigation controller
SlideMenuOptions.contentViewScale = 1.0
let controller = SlideMenuController(mainViewController: nvc, leftMenuViewController: drawerViewController)
self.presentViewController(controller, animated: true, completion: nil)
case .Failure(let error):
print("Request failed with error: \(error)")
self.verificationRequested = false;
self.registerView.changeToPhoneNumberUI()
}
}
}
/*
* sendPhoneNumber sends a phone number to the server to request an account (via verification code)
*/
func sendPhoneNumber() {
let phoneNumber = "+1" + self.registerView.areaCodeView.text! + self.registerView.lineNumberView.text!
let requestAuthParameters = [
"phone-#": phoneNumber
]
Alamofire.request(.POST, Global.serverURL + "/account/request", parameters: requestAuthParameters, encoding: .JSON)
.responseString { response in
debugPrint(response)
switch response.result {
case .Success(_):
NSUserDefaults.standardUserDefaults().setObject(phoneNumber, forKey: "phoneNumber")
// The next time goButtonClickHandler() is invoked, we are going to be requesting a verification
self.verificationRequested = true;
self.registerView.changeToVerificationUI()
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
}
/*
* Set max length of input fields
*/
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var allowedLength: Int
switch textField.tag {
case RegisterView.areaCodeViewTag:
allowedLength = Global.areaCodeLength
if textField.text?.characters.count == allowedLength && string.characters.count != 0 {
self.registerView.lineNumberView.becomeFirstResponder()
allowedLength = Global.lineNumberLength
}
case RegisterView.lineNumberViewTag:
allowedLength = Global.lineNumberLength
if textField.text?.characters.count == 0 && string.characters.count == 0 && self.registerView.lineNumberView.text?.characters.count == 0 {
self.registerView.areaCodeView.becomeFirstResponder()
allowedLength = Global.areaCodeLength
}
case RegisterView.verificationCodeViewTag:
allowedLength = Global.verificationCodeLength
default:
allowedLength = 255
}
if textField.text?.characters.count >= allowedLength && range.length == 0 {
// Change not allowed
return false
}
else {
// Change allowed
return true
}
}
} | apache-2.0 | 58f167c860f59e5c788de7fb2fb23156 | 43.37931 | 183 | 0.633338 | 5.779192 | false | false | false | false |
xwu/swift | test/IRGen/objc_bridge.swift | 8 | 11035 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-ir -primary-file %s | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// CHECK: [[GETTER_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00"
// CHECK: [[SETTER_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[DEALLOC_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: @_INSTANCE_METHODS__TtC11objc_bridge3Bas = internal constant { i32, i32, [17 x { i8*, i8*, i8* }] } {
// CHECK: i32 24,
// CHECK: i32 17,
// CHECK: [17 x { i8*, i8*, i8* }] [
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strRealPropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strRealPropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(strFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11strFakePropSSvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([16 x i8], [16 x i8]* @"\01L_selector_data(setStrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC11strFakePropSSvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrRealProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrRealProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(nsstrFakeProp)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvgTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* @"\01L_selector_data(setNsstrFakeProp:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(strResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC9strResultSSyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]*}} x i8], [{{[0-9]*}} x i8]* @"\01L_selector_data(strArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC6strArg1sySS_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* @"\01L_selector_data(nsstrResult)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* @"\01L_selector_data(nsstrArgWithS:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*, [[OPAQUE:.*]]*)* @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast ([[OPAQUE:.*]]* ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCACycfcTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfDTo" to i8*)
// CHECK: },
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"\01L_selector_data(acceptSet:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* @{{[0-9]+}}, i64 0, i64 0),
// CHECK: i8* bitcast (void (%3*, i8*, %4*)* @"$s11objc_bridge3BasC9acceptSetyyShyACGFTo" to i8*)
// CHECK: }
// CHECK: { i8*, i8*, i8* } {
// CHECK: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @{{.*}}, i64 0, i64 0),
// CHECK: i8* bitcast (void ([[OPAQUE:.*]]*, i8*)* @"$s11objc_bridge3BasCfETo" to i8*)
// CHECK: }
// CHECK: ]
// CHECK: }, section "__DATA, {{.*}}", align 8
// CHECK: @_PROPERTIES__TtC11objc_bridge3Bas = internal constant { i32, i32, [5 x { i8*, i8* }] } {
// CHECK: [[OBJC_BLOCK_PROPERTY:@.*]] = private unnamed_addr constant [8 x i8] c"T@?,N,C\00"
// CHECK: @_PROPERTIES__TtC11objc_bridge21OptionalBlockProperty = internal constant {{.*}} [[OBJC_BLOCK_PROPERTY]]
func getDescription(_ o: NSObject) -> String {
return o.description
}
func getUppercaseString(_ s: NSString) -> String {
return s.uppercase()
}
// @interface Foo -(void) setFoo: (NSString*)s; @end
func setFoo(_ f: Foo, s: String) {
f.setFoo(s)
}
// NSString *bar(int);
func callBar() -> String {
return bar(0)
}
// void setBar(NSString *s);
func callSetBar(_ s: String) {
setBar(s)
}
var NSS : NSString = NSString()
// -- NSString methods don't convert 'self'
extension NSString {
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE13nsstrFakePropABvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$sSo8NSStringC11objc_bridgeE11nsstrResultAByFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$sSo8NSStringC11objc_bridgeE8nsstrArg1syAB_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func nsstrArg(s s: NSString) { }
}
class Bas : NSObject {
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strRealPropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strRealPropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var strRealProp : String
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11strFakePropSSvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC11strFakePropSSvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var strFakeProp : String {
get {
return ""
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvgTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrRealPropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrRealProp : NSString
// CHECK: define hidden swiftcc %TSo8NSStringC* @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvg"(%T11objc_bridge3BasC* swiftself %0) {{.*}} {
// CHECK: define internal void @"$s11objc_bridge3BasC13nsstrFakePropSo8NSStringCvsTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc var nsstrFakeProp : NSString {
get {
return NSS
}
set {}
}
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC9strResultSSyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func strResult() -> String { return "" }
// CHECK: define internal void @"$s11objc_bridge3BasC6strArg1sySS_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func strArg(s s: String) { }
// CHECK: define internal [[OPAQUE:.*]]* @"$s11objc_bridge3BasC11nsstrResultSo8NSStringCyFTo"([[OPAQUE:.*]]* %0, i8* %1) {{[#0-9]*}} {
@objc func nsstrResult() -> NSString { return NSS }
// CHECK: define internal void @"$s11objc_bridge3BasC8nsstrArg1sySo8NSStringC_tFTo"([[OPAQUE:.*]]* %0, i8* %1, [[OPAQUE:.*]]* %2) {{[#0-9]*}} {
@objc func nsstrArg(s s: NSString) { }
override init() {
strRealProp = String()
nsstrRealProp = NSString()
super.init()
}
deinit { var x = 10 }
override var hash: Int { return 0 }
@objc func acceptSet(_ set: Set<Bas>) { }
}
func ==(lhs: Bas, rhs: Bas) -> Bool { return true }
class OptionalBlockProperty: NSObject {
@objc var x: (([AnyObject]) -> [AnyObject])?
}
| apache-2.0 | 585cf5bd05fea0438c0eccf40b195c57 | 53.359606 | 147 | 0.580517 | 3.032426 | false | false | false | false |
erduoniba/FDDUITableViewDemoSwift | FDDUITableViewDemoSwift/FDDBaseRepo/FDDBaseCellModel.swift | 1 | 1066 | //
// FDDBaseCellModel.swift
// FDDUITableViewDemoSwift
//
// Created by denglibing on 2017/2/9.
// Copyright © 2017年 denglibing. All rights reserved.
// Demo: https://github.com/erduoniba/FDDUITableViewDemoSwift
//
import UIKit
open class FDDBaseCellModel: NSObject {
open var cellData: AnyObject?
open var cellClass: AnyClass?
open weak var delegate: AnyObject?
open var cellHeight: Float = 44
open var staticCell: UITableViewCell?
open var cellReuseIdentifier: String?
override init() {
super.init()
}
public convenience init(cellClass: AnyClass?, cellHeight: Float, cellData: AnyObject?) {
self.init()
self.cellClass = cellClass
self.cellHeight = cellHeight
self.cellData = cellData
}
open class func modelWithCellClass(_ cellClass: AnyClass?, cellHeight: Float, cellData: AnyObject?) -> FDDBaseCellModel {
let cellModel: FDDBaseCellModel = FDDBaseCellModel(cellClass: cellClass, cellHeight: cellHeight, cellData: cellData)
return cellModel
}
}
| mit | e9327e8f2f69861d9b510431d5211b58 | 29.371429 | 125 | 0.699906 | 4.374486 | false | false | false | false |
yanyuqingshi/ios-charts | Charts/Classes/Data/BubbleChartDataEntry.swift | 1 | 1226 | //
// BubbleDataEntry.swift
// Charts
//
// Bubble chart implementation:
// Copyright 2015 Pierre-Marc Airoldi
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class BubbleChartDataEntry: ChartDataEntry
{
/// The size of the bubble.
public var size = CGFloat(0.0)
/// :xIndex: The index on the x-axis.
/// :val: The value on the y-axis.
/// :size: The size of the bubble.
public init(xIndex: Int, value: Double, size: CGFloat)
{
super.init(value: value, xIndex: xIndex)
self.size = size
}
/// :xIndex: The index on the x-axis.
/// :val: The value on the y-axis.
/// :size: The size of the bubble.
/// :data: Spot for additional data this Entry represents.
public init(xIndex: Int, value: Double, size: CGFloat, data: AnyObject?)
{
super.init(value: value, xIndex: xIndex, data: data)
self.size = size
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! BubbleChartDataEntry;
copy.size = size;
return copy;
}
} | apache-2.0 | 7e38195949ed223e0d893558009af434 | 24.5625 | 76 | 0.607667 | 3.929487 | false | false | false | false |
qutheory/vapor | Sources/XCTVapor/XCTHTTPRequest.swift | 2 | 2072 | public struct XCTHTTPRequest {
public var method: HTTPMethod
public var url: URI
public var headers: HTTPHeaders
public var body: ByteBuffer
private struct _ContentContainer: ContentContainer {
var body: ByteBuffer
var headers: HTTPHeaders
var contentType: HTTPMediaType? {
return self.headers.contentType
}
mutating func encode<E>(_ encodable: E, using encoder: ContentEncoder) throws where E : Encodable {
try encoder.encode(encodable, to: &self.body, headers: &self.headers)
}
func decode<D>(_ decodable: D.Type, using decoder: ContentDecoder) throws -> D where D : Decodable {
fatalError("Decoding from test request is not supported.")
}
mutating func encode<C>(_ content: C, using encoder: ContentEncoder) throws where C : Content {
var content = content
try content.beforeEncode()
try encoder.encode(content, to: &self.body, headers: &self.headers)
}
}
public var content: ContentContainer {
get {
_ContentContainer(body: self.body, headers: self.headers)
}
set {
let content = (newValue as! _ContentContainer)
self.body = content.body
self.headers = content.headers
}
}
private struct _URLQueryContainer: URLQueryContainer {
var url: URI
func decode<D>(_ decodable: D.Type, using decoder: URLQueryDecoder) throws -> D
where D: Decodable
{
fatalError("Decoding from test request is not supported.")
}
mutating func encode<E>(_ encodable: E, using encoder: URLQueryEncoder) throws
where E: Encodable
{
try encoder.encode(encodable, to: &self.url)
}
}
public var query: URLQueryContainer {
get {
_URLQueryContainer(url: url)
}
set {
let query = (newValue as! _URLQueryContainer)
self.url = query.url
}
}
}
| mit | c0ef84d323b91372fff660f2880ec3eb | 30.393939 | 108 | 0.592181 | 4.852459 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/View/Recent/VRecentHeader.swift | 1 | 1239 | import UIKit
class VRecentHeader:UICollectionReusableView
{
private weak var label:UILabel!
private let kLabelMargin:CGFloat = 10
private let kLabelHeight:CGFloat = 34
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.regular(size:15)
label.textColor = UIColor(white:0.3, alpha:1)
self.label = label
addSubview(label)
NSLayoutConstraint.bottomToBottom(
view:label,
toView:self)
NSLayoutConstraint.height(
view:label,
constant:kLabelHeight)
NSLayoutConstraint.equalsHorizontal(
view:label,
toView:self,
margin:kLabelMargin)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: public
func config(model:MRecentDay)
{
label.text = model.title
}
}
| mit | 8c66353defb6cc93eee1fe7f4d455bdb | 24.285714 | 63 | 0.603713 | 5.205882 | false | false | false | false |
Bunn/macGist | macGist/GistCell.swift | 1 | 1971 | //
// GistCell.swift
// macGist
//
// Created by Fernando Bunn on 09/01/2018.
// Copyright © 2018 Fernando Bunn. All rights reserved.
//
//
import Cocoa
class GistCell: NSTableCellView {
@IBOutlet private weak var titleLabel: NSTextField!
@IBOutlet private weak var subtitleLabel: NSTextField!
@IBOutlet private weak var lockImageView: NSImageView!
static var dateFormatter: DateFormatter = {
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
return dateFormatter
}()
var selected: Bool = false {
didSet {
if oldValue != selected {
setupColors()
}
}
}
var gist: Gist? {
didSet {
if let gist = gist {
if gist.description.count == 0 {
if let file = gist.gistFiles.first {
titleLabel.stringValue = file.name
}
} else {
titleLabel.stringValue = gist.description
}
subtitleLabel.stringValue = "Created at: \(GistCell.dateFormatter.string(from: gist.createdAt))"
lockImageView.image = gist.publicItem ? #imageLiteral(resourceName: "lock_opened") : #imageLiteral(resourceName: "lock_closed")
setupColors()
}
}
}
private func setupColors() {
if selected {
titleLabel.textColor = .white
subtitleLabel.textColor = .white
lockImageView.image = lockImageView.image?.tinting(with: .white)
} else {
titleLabel.textColor = .darkGray
subtitleLabel.textColor = .darkGray
lockImageView.image = lockImageView.image?.tinting(with: .darkGray)
}
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
}
| mit | 1db1fa6be4bca2a9af9b5f67b9130dd1 | 29.307692 | 143 | 0.556345 | 5.184211 | false | false | false | false |
ashetty1/kedge | vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-generator/examples/bookstore/Sources/Server/main.swift | 131 | 4133 | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Bookstore
class Server : Service {
private var shelves : [Int64:Shelf] = [:]
private var books : [Int64:[Int64:Book]] = [:]
private var lastShelfIndex : Int64 = 0
private var lastBookIndex : Int64 = 0
// Return all shelves in the bookstore.
func listShelves () throws -> ListShelvesResponses {
let responses = ListShelvesResponses()
let response = ListShelvesResponse()
var shelves : [Shelf] = []
for pair in self.shelves {
shelves.append(pair.value)
}
response.shelves = shelves
responses.ok = response
return responses
}
// Create a new shelf in the bookstore.
func createShelf (_ parameters : CreateShelfParameters) throws -> CreateShelfResponses {
lastShelfIndex += 1
let shelf = parameters.shelf
shelf.name = "shelves/\(lastShelfIndex)"
shelves[lastShelfIndex] = shelf
let responses = CreateShelfResponses()
responses.ok = shelf
return responses
}
// Delete all shelves.
func deleteShelves () throws {
shelves = [:]
books = [:]
lastShelfIndex = 0
lastBookIndex = 0
}
// Get a single shelf resource with the given ID.
func getShelf (_ parameters : GetShelfParameters) throws -> GetShelfResponses {
let responses = GetShelfResponses()
if let shelf : Shelf = shelves[parameters.shelf] {
responses.ok = shelf
} else {
let err = Error()
err.code = 404
err.message = "not found"
responses.error = err
}
return responses
}
// Delete a single shelf with the given ID.
func deleteShelf (_ parameters : DeleteShelfParameters) throws {
shelves[parameters.shelf] = nil
books[parameters.shelf] = nil
}
// Return all books in a shelf with the given ID.
func listBooks (_ parameters : ListBooksParameters) throws -> ListBooksResponses {
let responses = ListBooksResponses()
let response = ListBooksResponse()
var books : [Book] = []
if let shelfBooks = self.books[parameters.shelf] {
for pair in shelfBooks {
books.append(pair.value)
}
}
response.books = books
responses.ok = response
return responses
}
// Create a new book on the shelf.
func createBook (_ parameters : CreateBookParameters) throws -> CreateBookResponses {
let responses = CreateBookResponses()
lastBookIndex += 1
let shelf = parameters.shelf
let book = parameters.book
book.name = "shelves/\(shelf)/books/\(lastBookIndex)"
if var shelfBooks = self.books[shelf] {
shelfBooks[lastBookIndex] = book
self.books[shelf] = shelfBooks
} else {
var shelfBooks : [Int64:Book] = [:]
shelfBooks[lastBookIndex] = book
self.books[shelf] = shelfBooks
}
responses.ok = book
return responses
}
// Get a single book with a given ID from a shelf.
func getBook (_ parameters : GetBookParameters) throws -> GetBookResponses {
let responses = GetBookResponses()
if let shelfBooks = self.books[parameters.shelf],
let book = shelfBooks[parameters.book] {
responses.ok = book
} else {
let err = Error()
err.code = 404
err.message = "not found"
responses.error = err
}
return responses
}
// Delete a single book with a given ID from a shelf.
func deleteBook (_ parameters : DeleteBookParameters) throws {
if var shelfBooks = self.books[parameters.shelf] {
shelfBooks[parameters.book] = nil
self.books[parameters.shelf] = shelfBooks
}
}
}
initialize(service:Server(), port:8080)
run()
| apache-2.0 | c0d6aaeb5f7c96290565d89286c2f1d3 | 31.289063 | 90 | 0.675538 | 4.063913 | false | false | false | false |
Guanzhangpeng/ZPSegmentBar | ZPSegmentBar/Classes/ZPSegmentBarView.swift | 1 | 1727 | //
// ZPSegmentBarView.swift
// ZPSegmentBar
//
// Created by 管章鹏 on 17/3/9.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import UIKit
public class ZPSegmentBarView: UIView {
var titles :[String]
var style :ZPStyle
var childVcs :[UIViewController]
var parentVc : UIViewController
public init(frame:CGRect,titles:[String],style : ZPStyle,childVcs:[UIViewController],parentVc:UIViewController ) {
self.titles=titles
self.style=style
self.childVcs=childVcs
self.parentVc=parentVc
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK - UI布局
extension ZPSegmentBarView
{
fileprivate func setupUI()
{
//1.0 创建TitleView
let titleFrame = CGRect(x: 0, y: 64, width: bounds.width, height: style.titleHeight)
let titleView = ZPTitleView(frame: titleFrame, titles: titles, style: style)
addSubview(titleView)
titleView.backgroundColor = style.titleViewBackgroundColor
//2.0 创建ContentView
let contentFrame = CGRect(x: 0, y: titleView.frame.maxY, width: bounds.width, height: bounds.height-style.titleHeight)
let contentView = ZPContentView(frame: contentFrame, childVcs: childVcs, parentVc: parentVc)
addSubview(contentView)
// 3.0 让ContentView成为titleView的代理
titleView.delegate = contentView
contentView.delegate = titleView
//3.0 设置TitleView和ContentView之间的关联
}
}
| mit | f39105c56feab508e54c71030d45210b | 25.634921 | 126 | 0.63528 | 4.427441 | false | false | false | false |
ptsochantaris/trailer-cli | Sources/trailer/Data/Models/Review.swift | 1 | 6861 | //
// Review.swift
// trailer
//
// Created by Paul Tsochantaris on 18/08/2017.
// Copyright © 2017 Paul Tsochantaris. All rights reserved.
//
import Foundation
enum ReviewState: String, Codable {
case pending, commented, approved, changes_requested, dimissed
init?(rawValue: String) {
switch rawValue.lowercased() {
case "pending": self = ReviewState.pending
case "commented": self = ReviewState.commented
case "approved": self = ReviewState.approved
case "changes_requested": self = ReviewState.changes_requested
case "dimissed": self = ReviewState.dimissed
default: return nil
}
}
}
struct Review: Item, Announceable {
var id: String
var parents: [String: [Relationship]]
var syncState: SyncState
var elementType: String
static var allItems = [String: Review]()
static let idField = "id"
var state = ReviewState.pending
var body = ""
var viewerDidAuthor = false
var createdAt = Date.distantPast
var updatedAt = Date.distantPast
var syncNeedsComments = false
var comments: [Comment] {
children(field: "comments")
}
private enum CodingKeys: CodingKey {
case id
case parents
case elementType
case state
case body
case viewerDidAuthor
case createdAt
case updatedAt
}
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(String.self, forKey: .id)
parents = try c.decode([String: [Relationship]].self, forKey: .parents)
elementType = try c.decode(String.self, forKey: .elementType)
state = ReviewState(rawValue: try c.decode(String.self, forKey: .state)) ?? ReviewState.pending
body = try c.decode(String.self, forKey: .body)
viewerDidAuthor = try c.decode(Bool.self, forKey: .viewerDidAuthor)
createdAt = try c.decode(Date.self, forKey: .createdAt)
updatedAt = try c.decode(Date.self, forKey: .updatedAt)
syncState = .none
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(id, forKey: .id)
try c.encode(parents, forKey: .parents)
try c.encode(elementType, forKey: .elementType)
try c.encode(state, forKey: .state)
try c.encode(body, forKey: .body)
try c.encode(viewerDidAuthor, forKey: .viewerDidAuthor)
try c.encode(createdAt, forKey: .createdAt)
try c.encode(updatedAt, forKey: .updatedAt)
}
mutating func apply(_ node: [AnyHashable: Any]) -> Bool {
guard node.keys.count > 5 else { return false }
syncNeedsComments = (node["comments"] as? [AnyHashable: Any])?["totalCount"] as? Int ?? 0 > 0
state = ReviewState(rawValue: node["state"] as? String ?? "PENDING") ?? ReviewState.pending
body = node["body"] as? String ?? ""
createdAt = GHDateFormatter.parseGH8601(node["createdAt"] as? String) ?? Date.distantPast
updatedAt = GHDateFormatter.parseGH8601(node["updatedAt"] as? String) ?? Date.distantPast
viewerDidAuthor = node["viewerDidAuthor"] as? Bool ?? false
return true
}
init?(id: String, type: String, node: [AnyHashable: Any]) {
self.id = id
parents = [String: [Relationship]]()
elementType = type
syncState = .new
if !apply(node) {
return nil
}
}
func announceIfNeeded(notificationMode: NotificationMode) {
if notificationMode != .consoleCommentsAndReviews || syncState != .new { return }
if viewerDidAuthor { return }
if let p = pullRequest, p.syncState != .new, let re = pullRequest?.repo, let a = p.author?.login, re.syncState != .new {
let r = re.nameWithOwner
let d: String
switch state {
case .approved:
d = "[\(r)] @\(a) reviewed [G*(approving)*]"
case .changes_requested:
d = "[\(r)] @\(a) reviewed [R*(requesting changes)*]"
case .commented where body.hasItems:
d = "[\(r)] @\(a) reviewed"
default:
return
}
Notifications.notify(title: d, subtitle: "PR #\(p.number) \(p.title))", details: body, relatedDate: createdAt)
}
}
private func printHeader() {
if let a = author?.login {
switch state {
case .approved:
log("[![*@\(a)*] \(agoFormat(prefix: "[G*Approved Changes*] ", since: createdAt))!]")
case .changes_requested:
log("[![*@\(a)*] \(agoFormat(prefix: "[R*Requested Changes*] ", since: createdAt))!]")
default:
log("[![*@\(a)*] \(agoFormat(prefix: "Reviewed ", since: createdAt))!]")
}
}
}
func printDetails() {
printHeader()
if body.hasItems {
log(body.trimmingCharacters(in: .whitespacesAndNewlines), unformatted: true)
log()
}
}
func printSummaryLine() {
printHeader()
log()
}
var pullRequest: PullRequest? {
if let parentId = parents["PullRequest:reviews"]?.first?.parentId {
return PullRequest.allItems[parentId]
}
return nil
}
var author: User? {
children(field: "author").first
}
mutating func setChildrenSyncStatus(_ status: SyncState) {
if var u = author {
u.setSyncStatus(status, andChildren: true)
User.allItems[u.id] = u
}
for c in comments {
var C = c
C.setSyncStatus(status, andChildren: true)
Comment.allItems[c.id] = C
}
}
var mentionsMe: Bool {
if body.localizedCaseInsensitiveContains(config.myLogin) {
return true
}
return comments.contains { $0.mentionsMe }
}
func includes(text: String) -> Bool {
if body.localizedCaseInsensitiveContains(text) { return true }
return comments.contains { $0.includes(text: text) }
}
static let fragment = Fragment(name: "reviewFields", on: "PullRequestReview", elements: [
Field.id,
Field(name: "body"),
Field(name: "state"),
Field(name: "viewerDidAuthor"),
Field(name: "createdAt"),
Field(name: "updatedAt"),
Group(name: "author", fields: [User.fragment]),
Group(name: "comments", fields: [Field(name: "totalCount")])
])
static let commentsFragment = Fragment(name: "ReviewCommentsFragment", on: "PullRequestReview", elements: [
Field.id, // not using fragment, no need to re-parse
Group(name: "comments", fields: [Comment.fragmentForReviews], paging: .largePage)
])
}
| mit | 89d1eac071586cbacde0734388805d1b | 32.960396 | 128 | 0.590816 | 4.218942 | false | false | false | false |
Aioria1314/WeiBo | WeiBo/WeiBo/Classes/Views/Main/ZXCVisitorView.swift | 1 | 4925 | //
// ZXCVisitorView.swift
// WeiBo
//
// Created by Aioria on 2017/3/27.
// Copyright © 2017年 Aioria. All rights reserved.
//
import UIKit
import SnapKit
class ZXCVisitorView: UIView {
private lazy var cycleImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
var loginOrRegisterClosure: (()->())?
private lazy var maskImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
private lazy var homeImageView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house"))
private lazy var messageLabel: UILabel = {
let lab = UILabel()
lab.numberOfLines = 2
lab.textColor = UIColor.gray
lab.font = UIFont.systemFont(ofSize: 12)
lab.textAlignment = .center
lab.text = "111111111111111"
return lab
}()
private lazy var btnRegister: UIButton = {
let btn = UIButton()
btn.setTitle("注册", for: .normal)
btn.addTarget(self, action: #selector(loginAndRegisterAction), for: .touchUpInside)
btn.setTitleColor(UIColor.darkGray, for: .normal)
btn.setTitleColor(UIColor.orange, for: .highlighted)
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .normal)
btn.adjustsImageWhenHighlighted = false
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
return btn
}()
private lazy var btnLogin: UIButton = {
let btn = UIButton()
btn.setTitle("登陆", for: .normal)
btn.addTarget(self, action: #selector(loginAndRegisterAction), for: .touchUpInside)
btn.setTitleColor(UIColor.darkGray, for: .normal)
btn.setTitleColor(UIColor.orange, for: .highlighted)
btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .normal)
btn.adjustsImageWhenHighlighted = false
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
addSubview(cycleImageView)
addSubview(maskImageView)
addSubview(homeImageView)
addSubview(messageLabel)
addSubview(btnRegister)
addSubview(btnLogin)
cycleImageView.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
maskImageView.snp.makeConstraints { (make) in
make.center.equalTo(cycleImageView)
}
homeImageView.snp.makeConstraints { (make) in
make.center.equalTo(maskImageView)
}
messageLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(homeImageView)
make.top.equalTo(maskImageView.snp.bottom)
make.width.equalTo(224)
}
btnRegister.snp.makeConstraints { (make) in
make.left.equalTo(messageLabel)
make.top.equalTo(messageLabel.snp.bottom).offset(10)
make.size.equalTo(CGSize(width: 80, height: 35))
}
btnLogin.snp.makeConstraints { (make) in
make.right.equalTo(messageLabel)
make.top.equalTo(btnRegister)
make.size.equalTo(btnRegister)
}
// startAnimation()
// cycleImageView.translatesAutoresizingMaskIntoConstraints = false
//
// addConstraint(NSLayoutConstraint(item: cycleImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
// addConstraint(NSLayoutConstraint(item: cycleImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
}
private func startAnimation() {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.toValue = 2 * Double.pi
animation.duration = 20
animation.repeatCount = MAXFLOAT
animation.isRemovedOnCompletion = false
cycleImageView.layer.add(animation, forKey: nil)
}
func updateVisitorInfo(imgName: String?, message: String?)
{
if let imageName = imgName, let msg = message
{
homeImageView.image = UIImage(named: imageName)
messageLabel.text = msg
cycleImageView.isHidden = true
}
else
{
startAnimation()
}
}
@objc private func loginAndRegisterAction() {
loginOrRegisterClosure?()
}
}
| mit | f42375cf14d7efa0154dee0ec50abed9 | 30.299363 | 168 | 0.608262 | 4.846154 | false | false | false | false |
apple/swift-package-manager | Sources/Workspace/ManagedDependency.swift | 2 | 9069 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basics
import PackageGraph
import PackageModel
import SourceControl
import TSCBasic
extension Workspace {
/// An individual managed dependency.
///
/// Each dependency will have a checkout containing the sources at a
/// particular revision, and may have an associated version.
public struct ManagedDependency: Equatable {
/// Represents the state of the managed dependency.
public indirect enum State: Equatable, CustomStringConvertible {
/// The dependency is a local package on the file system.
case fileSystem(AbsolutePath)
/// The dependency is a managed source control checkout.
case sourceControlCheckout(CheckoutState)
/// The dependency is downloaded from a registry.
case registryDownload(version: Version)
/// The dependency is in edited state.
///
/// If the path is non-nil, the dependency is managed by a user and is
/// located at the path. In other words, this dependency is being used
/// for top of the tree style development.
case edited(basedOn: ManagedDependency?, unmanagedPath: AbsolutePath?)
case custom(version: Version, path: AbsolutePath)
public var description: String {
switch self {
case .fileSystem(let path):
return "fileSystem (\(path))"
case .sourceControlCheckout(let checkoutState):
return "sourceControlCheckout (\(checkoutState))"
case .registryDownload(let version):
return "registryDownload (\(version))"
case .edited:
return "edited"
case .custom:
return "custom"
}
}
}
/// The package reference.
public let packageRef: PackageReference
/// The state of the managed dependency.
public let state: State
/// The checked out path of the dependency on disk, relative to the workspace checkouts path.
public let subpath: RelativePath
internal init(
packageRef: PackageReference,
state: State,
subpath: RelativePath
) {
self.packageRef = packageRef
self.subpath = subpath
self.state = state
}
/// Create an editable managed dependency based on a dependency which
/// was *not* in edit state.
///
/// - Parameters:
/// - subpath: The subpath inside the editable directory.
/// - unmanagedPath: A custom absolute path instead of the subpath.
public func edited(subpath: RelativePath, unmanagedPath: AbsolutePath?) throws -> ManagedDependency {
guard case .sourceControlCheckout = self.state else {
throw InternalError("invalid dependency state: \(self.state)")
}
return ManagedDependency(
packageRef: self.packageRef,
state: .edited(basedOn: self, unmanagedPath: unmanagedPath),
subpath: subpath
)
}
/// Create a dependency present locally on the filesystem.
public static func fileSystem(
packageRef: PackageReference
) throws -> ManagedDependency {
switch packageRef.kind {
case .root(let path), .fileSystem(let path), .localSourceControl(let path):
return ManagedDependency(
packageRef: packageRef,
state: .fileSystem(path),
// FIXME: This is just a fake entry, we should fix it.
subpath: RelativePath(packageRef.identity.description)
)
default:
throw InternalError("invalid package type: \(packageRef.kind)")
}
}
/// Create a source control dependency checked out
public static func sourceControlCheckout(
packageRef: PackageReference,
state: CheckoutState,
subpath: RelativePath
) throws -> ManagedDependency {
switch packageRef.kind {
case .localSourceControl, .remoteSourceControl:
return ManagedDependency(
packageRef: packageRef,
state: .sourceControlCheckout(state),
subpath: subpath
)
default:
throw InternalError("invalid package type: \(packageRef.kind)")
}
}
/// Create a registry dependency downloaded
public static func registryDownload(
packageRef: PackageReference,
version: Version,
subpath: RelativePath
) throws -> ManagedDependency {
guard case .registry = packageRef.kind else {
throw InternalError("invalid package type: \(packageRef.kind)")
}
return ManagedDependency(
packageRef: packageRef,
state: .registryDownload(version: version),
subpath: subpath
)
}
/// Create an edited dependency
public static func edited(
packageRef: PackageReference,
subpath: RelativePath,
basedOn: ManagedDependency?,
unmanagedPath: AbsolutePath?
) -> ManagedDependency {
return ManagedDependency(
packageRef: packageRef,
state: .edited(basedOn: basedOn, unmanagedPath: unmanagedPath),
subpath: subpath
)
}
}
}
extension Workspace.ManagedDependency: CustomStringConvertible {
public var description: String {
return "<ManagedDependency: \(self.packageRef.identity) \(self.state)>"
}
}
// MARK: - ManagedDependencies
extension Workspace {
/// A collection of managed dependencies.
final public class ManagedDependencies {
private var dependencies: [PackageIdentity: ManagedDependency]
init() {
self.dependencies = [:]
}
init(_ dependencies: [ManagedDependency]) throws {
// rdar://86857825 do not use Dictionary(uniqueKeysWithValues:) as it can crash the process when input is incorrect such as in older versions of SwiftPM
self.dependencies = [:]
for dependency in dependencies {
if self.dependencies[dependency.packageRef.identity] != nil {
throw StringError("\(dependency.packageRef.identity) already exists in managed dependencies")
}
self.dependencies[dependency.packageRef.identity] = dependency
}
}
public subscript(identity: PackageIdentity) -> ManagedDependency? {
return self.dependencies[identity]
}
// When loading manifests in Workspace, there are cases where we must also compare the location
// as it may attempt to load manifests for dependencies that have the same identity but from a different location
// (e.g. dependency is changed to a fork with the same identity)
public subscript(comparingLocation package: PackageReference) -> ManagedDependency? {
if let dependency = self.dependencies[package.identity], dependency.packageRef.equalsIncludingLocation(package) {
return dependency
}
return .none
}
public func add(_ dependency: ManagedDependency) {
self.dependencies[dependency.packageRef.identity] = dependency
}
public func remove(_ identity: PackageIdentity) {
self.dependencies[identity] = nil
}
}
}
extension Workspace.ManagedDependencies: Collection {
public typealias Index = Dictionary<PackageIdentity, Workspace.ManagedDependency>.Index
public typealias Element = Workspace.ManagedDependency
public var startIndex: Index {
self.dependencies.startIndex
}
public var endIndex: Index {
self.dependencies.endIndex
}
public subscript(index: Index) -> Element {
self.dependencies[index].value
}
public func index(after index: Index) -> Index {
self.dependencies.index(after: index)
}
}
extension Workspace.ManagedDependencies: CustomStringConvertible {
public var description: String {
"<ManagedDependencies: \(Array(self.dependencies.values))>"
}
}
| apache-2.0 | 5fbeb5adafb169d088387fedfd9708b0 | 36.630705 | 164 | 0.595766 | 5.696608 | false | false | false | false |
vakoc/particle-swift-cli | Sources/CliSecureStorage.swift | 1 | 3825 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import ParticleSwift
/// Simple implementation of a secure storage delegate to use a plain text json file at
/// ~/.particle-swift to manage OAuth
///
/// This class contains variables for username, password, OAuth client id, and OAuth secret
/// that can be programatically set. This is typically used only with the createToken command.
///
/// Creating a token once with this command will perist the token in the ~/.particle-swift file
/// such that credentials are not subsequently required
///
/// The ~/.particle-swift json file will look like
///
/// {
/// "oauthToken" : {
/// "created_at" : "2016-07-04T23:44:22.136-0700",
/// "token_type" : "bearer",
/// "refresh_token" : "23443q4aw4aw34w34w34w3a4aw34wa34w34w34w34",
/// "access_token" : "2342342asr23423wsr234aw4234235rqaw353w5w35w",
/// "expires_in" : 31536000
/// }
/// }
///
class CliSecureStorage: SecureStorage {
var username: String?
var password: String?
var client = "particle"
var secret = "particle"
var accessTokenOverride: String?
static let shared = CliSecureStorage()
lazy var dotFile: String = {
("~/.particle-swift" as NSString).expandingTildeInPath
}()
func username(_ realm: String) -> String? {
return self.username
}
func password(_ realm: String) -> String? {
return self.password
}
func oauthClientId(_ realm: String) -> String? {
return self.client
}
func oauthClientSecret(_ realm: String) -> String? {
return self.secret
}
func oauthToken(_ realm: String) -> OAuthToken? {
if let accessToken = accessTokenOverride {
return OAuthToken(with: [
"created_at" : "2016-06-27T22:58:52.579-0600",
"token_type" : "bearer",
"refresh_token" : "invalid-" + accessToken,
"access_token" : accessToken,
"expires_in" : 3153600000000
])
}
guard realm == ParticleSwiftInfo.realm && FileManager.default.fileExists(atPath: dotFile) == true,
let data = try? Data(contentsOf: URL(fileURLWithPath: dotFile), options: []),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = json as? [String : Any]
else { return nil }
if let tokenDict = dict["oauthToken"] as? [String : Any], let token = OAuthToken(with: tokenDict) {
return token
}
return nil
}
func updateOAuthToken(_ token: OAuthToken?, forRealm realm: String) {
guard realm == ParticleSwiftInfo.realm else { return }
var dotFileDict = [String : Any]()
if FileManager.default.fileExists(atPath: dotFile) == true,
let data = try? Data(contentsOf: URL(fileURLWithPath: dotFile), options: []),
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = json as? [String : AnyObject] {
dotFileDict = dict
}
dotFileDict["oauthToken"] = token?.dictionary ?? nil
do {
let savedData = try JSONSerialization.data(withJSONObject: dotFileDict, options: [.prettyPrinted])
try savedData.write(to: URL(fileURLWithPath: dotFile))
} catch {
warn("Failed to save updated oauth token to \(dotFile) with error \(error)")
}
}
}
| apache-2.0 | c79e56456004b99abb96c1d574897b0a | 33.142857 | 110 | 0.592312 | 4.282195 | false | false | false | false |
iOS-Swift-Developers/Swift | CacheSwift/CacheDemo_userDefault/CacheDemo1/ViewController.swift | 1 | 3354 | //
// ViewController.swift
// CacheDemo1
//
// Created by 韩俊强 on 2017/8/24.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
var textFiled = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "NSUserDefault"
let saveItem = UIBarButtonItem(title: "save", style: .done, target: self, action: #selector(save))
let readItem = UIBarButtonItem(title: "read", style: .done, target: self, action: #selector(ViewController.readInfo))
let deleteItem = UIBarButtonItem(title: "del", style: .done, target: self, action: #selector(ViewController.deleteInfo))
self.navigationItem.rightBarButtonItems = [saveItem, readItem, deleteItem]
setupUI()
}
override func loadView() {
super.loadView()
self.view.backgroundColor = UIColor.white
if self.responds(to: #selector(getter: UIViewController.edgesForExtendedLayout)) {
self.edgesForExtendedLayout = UIRectEdge()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - 保存
func saveInfo(_ name : String){
if 0 <= name.characters.count {
let userDefault = UserDefaults.standard
userDefault.set(name, forKey: "name")
userDefault.synchronize()
let alert = UIAlertController(title: nil, message: "保存成功", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - 读取
func readInfo() -> String {
let userDefault = UserDefaults.standard
let name = userDefault.object(forKey: "name") as? String
let alert = UIAlertController(title: nil, message: "读取成功:\(name)", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
if (name != nil) {
return name!
}
return ""
}
// MARK: - 删除
func deleteInfo() {
let userDefault = UserDefaults.standard
userDefault.removeObject(forKey: "name")
let alert = UIAlertController(title: nil, message: "删除成功", preferredStyle: .alert)
let okAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
func setupUI(){
textFiled = UITextField(frame: CGRect(x: 10, y: 10, width: 200, height: 30))
self.view.addSubview(textFiled)
textFiled.clearButtonMode = .whileEditing
textFiled.returnKeyType = .done
textFiled.delegate = self
textFiled.textColor = UIColor.red
textFiled.layer.borderColor = UIColor.black.cgColor
textFiled.layer.borderWidth = 1.0
}
func save() {
self.saveInfo(textFiled.text!)
}
}
| mit | 05711f260b608d871ad68d19b5d2f07f | 32.424242 | 128 | 0.615594 | 4.660563 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/View/MeaningTableViewCell.swift | 1 | 1623 | //
// MeaningTableViewCell.swift
// SAS Coffee
//
// Created by Duy Cao on 9/10/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
class MeaningTableViewCell: SuperTableViewCell {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBOutlet weak var lblExTitle: UILabel!
@IBOutlet weak var lblDeftitle: UILabel!
@IBOutlet weak var meaningtitle: UILabel!
@IBOutlet weak var wordType: UILabel!
@IBOutlet weak var phienam: UILabel!
@IBOutlet weak var definition: UILabel!
@IBOutlet weak var example: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func updateData(number : Int, str : String, obj : SuperModel){
}
override func updateData(anyObj : Any){
let data = anyObj as! DictionaryModel
self.meaningtitle.text = data.word
self.wordType.text = data.type
self.phienam.text = data.pronun
self.definition.text = data.def
self.lblDeftitle.text = (self.definition.text?.isEmpty)! ? "" : "Definition".localize()
self.example.text = data.example
self.lblExTitle.text = (self.example.text?.isEmpty)! ? "" : "Examples".localize()
}
}
| gpl-3.0 | d4a3af5a7d7c14ed673303a00b93b120 | 29.037037 | 95 | 0.645499 | 4.291005 | false | false | false | false |
mathewsheets/SwiftLearning | SwiftLearning.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift | 1 | 15364 | /*:
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
- - -
# Collection Types
* callout(Session Overview): Often times in programs you need to group data into a single container where the number of items is unknown. Swift provides 3 main containers known as *collection types* for storing collections of values. *Arrays* are ordered collections of values, *Sets* are unordered collections of unique values, and *Dictionaries* are unordered collections of key-value associations. Please visit the Swift Programming Language Guide section on [Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105) for more detail on collection types.
- - -
*/
import Foundation
/*:
## When you're allowed to change or *mutate* collections
Before we dive into detail on collection types, there's a suttle but easy way to indicate if you can mutate your collection type. We have already seen this with simple data types such as `Int` and `String`, you use `let` and `var`.
*/
let unmutableArray: [String] = ["One", "Two"]
//unmutableArray.append("Three")
var mutableArray: [Int] = [1, 2]
mutableArray.append(3)
//: > **Experiment**: Uncomment the unmutableArray.append statement.
/*:
## Arrays
An *Array* stores values of the same type, `Int`s, `String`s, ect. in ordered manner. The same value of the type can appear multiple times at different positions of the array.
*/
/*:
### Creating Arrays
Swift's *arrays* need to know what type of elements it will contain. You can create an empty array, create an array with a default size and values for each element, create an array by adding multiple arrays together and create arrays using literals.
*/
/*:
**A new empty Array**
> You can create an array explicitly with the type or when appropriate use type inference.
*/
var array: [Int] = [Int]()
array = []
print("array has \(array.count) items.")
//: The above statements show two ways to create a new array, allowing only to store `Int`s and print the number of elements.
/*:
**A new Array with default values**
>You can create an array with default values by using the *initializer* that accepts a default value and a repeat count of how many elements the array should contain
*/
let nineNines = [Int](repeating: 9, count: 9)
print("nineNines has \(nineNines.count) items.")
//: The above statements creates an array nine `Int`s all with a value of 9 and print the number of elements nineNines contains.
/*:
**A new Array by adding Arrays together**
>You can create an array by taking two *arrays* of the same type and adding them together usng the addition operator `+`. The new array's type is inferred from the type of the two arrays added together.
*/
let twoTwos = [Int](repeating: 2, count: 2)
let threeThrees = [Int](repeating: 3, count: 3)
let twosAndThrees = twoTwos + threeThrees
print("twosAndThrees has \(twosAndThrees.count) items.")
let threesAndTwos = threeThrees + twoTwos
print("threesAndTwos has \(threesAndTwos.count) items.")
//: The above statements creates two arrays by adding two other arrays together.
/*:
**A new Array using Array literal**
>You can create an array by using the literal syntax such as creating an array of `Ints` like `[1, 2, 3, 4, 5]`.
*/
let numbers = [1, 2, 3, 4, 5]
//: The above statement creates an array of numbers containing `Int` data types.
/*:
### Accessing data in an `Array`
You can access information and elements in an array by using the methods and properties provided by the `Array` collection type.
*/
print("numbers has \(numbers.count) elements")
if numbers.isEmpty {
print("numbers is empty")
} else {
print("numbers is not empty")
}
var firstNumber = numbers.first
var lastNumber = numbers.last
//: The above statements use properties of the `Array` collection type for count, empty, first element, and last element.
var secondNumber = numbers[1]
var thirdNumber = numbers[2]
//: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the array.
var oneTo4 = numbers[0...3]
//: You can also get a subset of elements using ranges.
let startIndex = numbers.startIndex
let endIndex = numbers.endIndex
numbers[numbers.index(after: startIndex)] // Get the element after the startIndex
numbers[numbers.index(before: endIndex)] // Get the element before the endIndex
numbers[numbers.index(startIndex, offsetBy: 1)] // Get the element using the startIndex as a starting point with an offset of 1
numbers[numbers.index(endIndex, offsetBy: -4)] // Get the element using the endIndex as a starting point with an offset of -4
//: And much like a String, you can use the various index methods to get elements.
/*:
### Modifying `Array`s
Using methods such as `append` and `remove` let you mutate an array.
*/
var mutableNumbers = numbers
mutableNumbers.append(6)
mutableNumbers.append(7)
mutableNumbers.append(8)
mutableNumbers.removeFirst()
mutableNumbers.removeLast()
mutableNumbers.remove(at: 0)
mutableNumbers.removeSubrange(mutableNumbers.index(mutableNumbers.startIndex, offsetBy: 2)..<mutableNumbers.endIndex)
mutableNumbers[0] = 1
mutableNumbers[1] = 2
mutableNumbers.append(3)
mutableNumbers.append(4)
mutableNumbers.append(5)
mutableNumbers[0...4] = [5, 6, 7, 8, 9]
mutableNumbers.insert(10, at: mutableNumbers.endIndex)
print(mutableNumbers)
//: The above statements using the `append`, `insert`, `remove` methods, *subscript syntax* as well as using a range to replace values of indexes.
/*:
### Iterating over elements in an `Array`
You use the `for-in` loop to iterate over elements in an `Array`
*/
for number in numbers {
print(number)
}
for (index, number) in numbers.enumerated() {
print("Item \(index + 1): \(number)")
}
//: The first `for-in` loop just pulls out the value for each element in the array, but the second `for-in` loops pulls out the index and value.
//: > **Experiment**: Use an `_` underscore instead of `name` in the above for loop. What happens?
/*:
## Sets
The `Set` collection type stores unique value of the same data type with no defined ordering. You use a `Set` instead of an `Array` when you need to ensure that an element only appears once.
*/
/*:
### Hash Values for Set Types
For a `Set` to ensure that it contains only unique values, each element must provide a value called the *hash value*. A *hash value* is an `Int` that is calulated and is the same for all objects that compare equally. Simple types such as `Int`s, `Double`s, `String`s, and `Bool`s all provide a *hash value* by default.
*/
let one = 1
let two = "two"
let three = Double.pi
let four = false
one.hashValue
two.hashValue
three.hashValue
four.hashValue
/*:
### Creating Sets
You create a new set collection type by specifing the data type for the element as in `Set<Element>` where `Element` is the data type the set is allowed to store.
*/
var alphabet = Set<Character>()
alphabet = []
/*:
The above statements create an empty set that is only allowed to store the Character data type. The second statment assigns *alphabet* to an empty array using the array literal and type inference.
*/
//: **A new Set using Array literal**
var alphabet1: Set<Character> = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
var alphabet2: Set = ["j", "k", "l", "m", "n", "o", "p", "q", "r"]
//: You can create a new `Set` using the array literal, but you need to type the variable or constant. `alphabet2` is a shorter way to create a `Set` because it can be inferred that all the values are of the same type, in this case `String`s. Notice that `alphabet1` and `alphabet2` are not of the same type.
/*:
### Accessing data in a `Set`
Similar to the `Array` collection type, you access information and elements in an `Set` using properties and methods of the `Set` collection type.
*/
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
print("alphabet has \(alphabet.count) elements")
if alphabet.isEmpty {
print("alphabet is empty")
} else {
print("alphabet is not empty")
}
var firstLetter = alphabet.first
//: The above statements use properties of the `Set` collection type for count, empty, and first element.
var secondLetter = alphabet[alphabet.index(alphabet.startIndex, offsetBy: 1)]
var thirdLetter = alphabet[alphabet.index(alphabet.startIndex, offsetBy: 2)]
//: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the set.
/*:
### Modifying elements in a Set
Using methods such as `insert` and `remove` let you mutate a set.
*/
alphabet.insert("n")
alphabet.insert("o")
alphabet.insert("p")
alphabet.removeFirst()
alphabet.remove(at: alphabet.startIndex)
alphabet.remove("o")
print(alphabet)
//: The above statements using the `insert` and `remove` methods to mutate the `Set`.
/*:
### Iterating over elements in a Set
You use the `for-in` loop to iterate over elements in an `Set`
*/
for letter in alphabet {
print(letter)
}
for (index, value) in alphabet.enumerated() {
print("index: \(index) - value: \(value)")
}
//: The first `for-in` loop just pulls out the value for each element in the set, but the second `for-in` first sorts the set before the looping starts.
/*:
### Set Operations
With the `Set` collection type, you can perform set operations in the mathematical sense.
*/
alphabet = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"]
var vowels : Set<Character> = ["a", "e", "i", "o", "u"]
//: **intersection(_:)** creates a new `Set` of only those values both sets have in common.
let intersection = vowels.intersection(alphabet)
//: **symmetricDifference(_:)** creates a new `Set` of values from either set, but not from both.
let symmetricDifference = vowels.symmetricDifference(alphabet)
//: **union(_:)** creates a new `Set` with all values from both sets.
let union = vowels.union(alphabet)
//: **subtracting(_:)** creates a new `Set` with values not in the specified set.
let subtracting = vowels.subtracting(alphabet)
/*:
### Set Membership and Equality
With the `Set` collection type, you can determine the membership of a set and if one set is equal to another.
*/
let family : Set = ["Matt", "Annie", "Samuel", "Jack", "Hudson", "Oliver"]
let parents : Set = ["Matt", "Annie"]
let children : Set = ["Samuel", "Jack", "Hudson", "Oliver"]
//: **“is equal” operator (==)** tests if one set is equal to another set.
family == parents.union(children)
parents == children
//: **isSubset(of:)** tests if all of the values of a set are contained in another set.
children.isSubset(of: family)
family.isSubset(of: children)
//: **isSuperset(of:)** test if a set contains all of the values in another set.
family.isSuperset(of: parents)
family.isSuperset(of: children)
children.isSuperset(of: family)
//: **isStrictSubset(of:) or isStrictSuperset(of:)** test if a set is a subset or superset, but not equal to, another set.
let old = parents
old.isStrictSubset(of: parents)
let boys: Set = ["Matt", "Samuel", "Jack", "Hudson", "Oliver"]
boys.isStrictSubset(of: family)
//: **isDisjoint(with:)** test if two sets have any values in common.
parents.isDisjoint(with: children)
family.isDisjoint(with: children)
/*:
## Dictionaries
A `Dictionary` stores associations or mappings between keys of the same data type and values of the same data type in a container with no defined ordering. The value of each element is tied to a unique *key*. It's this unique *key* that enables you to lookup values based on an identifer, just like a real dictionary having the word be the key and the definition the value.
*/
/*:
### Creating Dictionaries
Much like the `Array` and `Set` collection types, you need to specify the data type that the `Dictionary` is allowed to store. Unlike `Array`s and `Set`s, you need to specify the data type for the *Key* and the *Value*.
*/
var longhand: Dictionary<String, String>? = nil
var shorthand: [String: String]? = nil
/*:
Above shows a long and short way to create a dictionary.
*/
//: **A new empty Dictionary**
var titles = [String: String]()
titles["dad"] = "Matt"
titles = [:]
/*:
Above creates an empty `Dictionary`, adds an entry into `titles` and then assigns `titles` to an empty dictionary using the shorthand form and type inference.
*/
//: **A new Dictionary using Dictionary literal**
titles = ["dad": "Matt", "mom": "Annie", "child_1": "Sam", "child_2": "Jack", "child_3": "Hudson", "child_4": "Oliver"]
/*:
Above creates a `Dictionary` using the literal syntax. Notice the *key: value* mapping separated by a comma, all surrounded by square brackets.
*/
/*:
### Accessing data in a Dictionary
Like the `Array` and `Set` collection types, the `Dictionary` also has the `count` and `isEmpty` properties, but unlike arrays and sets, you access elements using a *key*.
*/
print("titles has \(titles.count) elements")
if titles.isEmpty {
print("titles is empty")
} else {
print("titles is not empty")
}
var dad = titles["dad"]
if dad != nil {
print(dad!)
}
/*:
Above statements use the `count` and `isEmpty` properties, as well as use the *key* to retrive a value. It's possible that you use a *key* that does not exist in the dictionary. The `Dictionary` collection type will always return the value as an *Optional*. You then next would need to check for `nil` and *unwrap* the optional to obtain the real value.
*/
/*:
### Modifying elements in a Dictionary
There are two techniques to add/update entries for the `Dictionary` collection type, by using the *subscript syntax* or using a method.
*/
titles["dog"] = "Carson"
titles["child_1"] = "Samuel"
var father = titles.updateValue("Mathew", forKey: "dad")
var cat = titles.updateValue("Fluffy", forKey: "cat")
titles["dog"] = nil
cat = titles.removeValue(forKey: "cat")
if cat != nil {
print("removed \(cat!)")
}
/*:
The above statements use both the *subscript syntax* and methods for add, updating, and removing entries of a dictionary. Notice that with the method technique, you are returned a value if if the entry exists in the dictionary.
*/
/*:
### Iterating over elements in a Dictionary
Just like the `Array` and `Set` collection types, you iterate over a dictionary using a `for-in` loop.
*/
for element in titles {
print("\(element.0): \(element.1)")
}
for (key, value) in titles {
print("\(key): \(value)")
}
for title in titles.keys {
print("title: \(title)")
}
for name in titles.values {
print("name: \(name)")
}
let titleNames = [String](titles.keys)
let names = [String](titles.values)
/*:
Above statements use the `for-in` loop to iterate over the `titles` giving you access to the *key* and *value*. You can also access only the *keys* or *values*.
*/
//: > **Experiment**: Create a array of dictionaries and iterate over the array printing the key and value of each dictionary
/*:
* callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC
- [Guide: Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105)
- - -
[Table of Contents](@first) | [Previous](@previous) | [Next](@next)
*/
| mit | b8852ad98f4ac2a1ab4102378c7d823f | 44.309735 | 690 | 0.717318 | 3.850589 | false | false | false | false |
duycao2506/SASCoffeeIOS | Pods/PopupDialog/PopupDialog/Classes/PopupDialogDefaultView.swift | 1 | 5764 | //
// PopupDialogView.swift
//
// Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk)
// Author - Martin Wildfeuer (http://www.mwfire.de)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
/// The main view of the popup dialog
final public class PopupDialogDefaultView: UIView {
// MARK: - Appearance
/// The font and size of the title label
@objc public dynamic var titleFont: UIFont {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
/// The color of the title label
@objc public dynamic var titleColor: UIColor? {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
/// The text alignment of the title label
@objc public dynamic var titleTextAlignment: NSTextAlignment {
get { return titleLabel.textAlignment }
set { titleLabel.textAlignment = newValue }
}
/// The font and size of the body label
@objc public dynamic var messageFont: UIFont {
get { return messageLabel.font }
set { messageLabel.font = newValue }
}
/// The color of the message label
@objc public dynamic var messageColor: UIColor? {
get { return messageLabel.textColor }
set { messageLabel.textColor = newValue}
}
/// The text alignment of the message label
@objc public dynamic var messageTextAlignment: NSTextAlignment {
get { return messageLabel.textAlignment }
set { messageLabel.textAlignment = newValue }
}
// MARK: - Views
/// The view that will contain the image, if set
internal lazy var imageView: UIImageView = {
let imageView = UIImageView(frame: .zero)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
/// The title label of the dialog
internal lazy var titleLabel: UILabel = {
let titleLabel = UILabel(frame: .zero)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.textColor = UIColor(white: 0.4, alpha: 1)
titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
return titleLabel
}()
/// The message label of the dialog
internal lazy var messageLabel: UILabel = {
let messageLabel = UILabel(frame: .zero)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.textColor = UIColor(white: 0.6, alpha: 1)
messageLabel.font = UIFont.systemFont(ofSize: 14)
return messageLabel
}()
/// The height constraint of the image view, 0 by default
internal var imageHeightConstraint: NSLayoutConstraint?
// MARK: - Initializers
internal override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View setup
internal func setupViews() {
// Self setup
translatesAutoresizingMaskIntoConstraints = false
// Add views
addSubview(imageView)
addSubview(titleLabel)
addSubview(messageLabel)
// Layout views
let views = ["imageView": imageView, "titleLabel": titleLabel, "messageLabel": messageLabel] as [String: Any]
var constraints = [NSLayoutConstraint]()
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[imageView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[titleLabel]-(==20@900)-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[messageLabel]-(==20@900)-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]-(==30@900)-[titleLabel]-(==8@900)-[messageLabel]-(==30@900)-|", options: [], metrics: nil, views: views)
// ImageView height constraint
imageHeightConstraint = NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 0, constant: 0)
if let imageHeightConstraint = imageHeightConstraint {
constraints.append(imageHeightConstraint)
}
// Activate constraints
NSLayoutConstraint.activate(constraints)
}
}
| gpl-3.0 | 72b40777fbb561cbbbf29b8b52627989 | 37.945946 | 192 | 0.679216 | 4.999133 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/QOS/Helpers/UDPStreamSender.swift | 1 | 9465 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************************************/
import Foundation
import CocoaAsyncSocket
///
struct UDPStreamSenderSettings {
var host: String
var port: UInt16 = 0
var delegateQueue: DispatchQueue
var sendResponse: Bool = false
var maxPackets: UInt16 = 5
var timeout: UInt64 = 10_000_000_000
var delay: UInt64 = 10_000
var writeOnly: Bool = false
var portIn: UInt16?
}
///
class UDPStreamSender: NSObject {
///
fileprivate let streamSenderQueue = DispatchQueue(label: "com.specure.rmbt.udp.streamSenderQueue", attributes: DispatchQueue.Attributes.concurrent)
///
fileprivate var udpSocket: GCDAsyncUdpSocket?
///
fileprivate let countDownLatch = CountDownLatch()
///
fileprivate var running = AtomicBoolean()
fileprivate var isStopped = true
//
///
weak var delegate: UDPStreamSenderDelegate?
///
fileprivate let settings: UDPStreamSenderSettings
//
///
fileprivate var packetsReceived: UInt16 = 0
///
fileprivate var packetsSent: UInt16 = 0
///
fileprivate let delayMS: UInt64
///
fileprivate let timeoutMS: UInt64
///
fileprivate let timeoutSec: Double
///
fileprivate var lastSentTimestampMS: UInt64 = 0
///
fileprivate var usleepOverhead: UInt64 = 0
//
deinit {
defer {
if self.isStopped == false {
self.stop()
}
}
}
///
required init(settings: UDPStreamSenderSettings) {
self.settings = settings
delayMS = settings.delay / NSEC_PER_MSEC
timeoutMS = settings.timeout / NSEC_PER_MSEC
timeoutSec = nsToSec(settings.timeout)
}
///
func stop() {
_ = running.testAndSet(false)
close()
}
///
fileprivate func connect() {
Log.logger.debug("connecting udp socket")
stop()
udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: streamSenderQueue)
udpSocket?.setupSocket()
isStopped = false
//
do {
if let portIn = settings.portIn {
try udpSocket?.bind(toPort: portIn)
}
try udpSocket?.connect(toHost: settings.host, onPort: settings.port)
_ = countDownLatch.await(200 * NSEC_PER_MSEC)
//
if !settings.writeOnly {
try udpSocket?.beginReceiving()
}
} catch {
self.stop()
Log.logger.debug("bindToPort error?: \(error)")
Log.logger.debug("connectToHost error?: \(error)") // TODO: check error (i.e. fail if error)
Log.logger.debug("receive error?: \(error)") // TODO: check error (i.e. fail if error)
}
}
///
fileprivate func close() {
isStopped = true
Log.logger.debug("closing udp socket")
udpSocket?.close()//AfterSending()
udpSocket?.setDelegate(nil)
udpSocket?.setDelegateQueue(nil)
udpSocket = nil
}
///
func send() -> Bool {
connect()
let startTimeMS = UInt64.currentTimeMillis()
let stopTimeMS: UInt64 = (timeoutMS > 0) ? timeoutMS + startTimeMS : 0
//
var dataToSend = NSMutableData()
var shouldSend = false
//
var hasTimeout = false
_ = running.testAndSet(true)
while (running.boolValue && (self.udpSocket != nil)) {
////////////////////////////////////
// check if should stop
if stopTimeMS > 0 && stopTimeMS < UInt64.currentTimeMillis() {
Log.logger.debug("stopping because of stopTimeMS")
hasTimeout = true
break
}
////////////////////////////////////
// check delay
Log.logger.verbose("currentTimeMS: \(UInt64.currentTimeMillis()), lastSentTimestampMS: \(self.lastSentTimestampMS)")
var currentDelay = UInt64.currentTimeMillis() - lastSentTimestampMS + usleepOverhead
Log.logger.verbose("current delay: \(currentDelay)")
currentDelay = (currentDelay > delayMS) ? 0 : delayMS - currentDelay
Log.logger.verbose("current delay2: \(currentDelay)")
if currentDelay > 0 {
let sleepMicroSeconds = UInt32(currentDelay * 1000)
let sleepDelay = UInt64.currentTimeMillis()
usleep(sleepMicroSeconds) // TODO: usleep has an average overhead of about 0-5ms!
let usleepCurrentOverhead = UInt64.currentTimeMillis() - sleepDelay
if usleepCurrentOverhead > 20 {
usleepOverhead = usleepCurrentOverhead - currentDelay
} else {
usleepOverhead = 0
}
Log.logger.verbose("usleep for \(currentDelay)ms took \(usleepCurrentOverhead)ms (overhead \(self.usleepOverhead))")
}
////////////////////////////////////
// send packet
if packetsSent < settings.maxPackets {
dataToSend = NSMutableData()
shouldSend = self.delegate?.udpStreamSender(self, willSendPacketWithNumber: self.packetsSent, data: &dataToSend) ?? false
if shouldSend {
lastSentTimestampMS = UInt64.currentTimeMillis()
udpSocket?.send(dataToSend as Data, withTimeout: timeoutSec, tag: Int(packetsSent)) // TAG == packet number
packetsSent += 1
//lastSentTimestampMS = currentTimeMillis()
}
}
////////////////////////////////////
// check for stop
if settings.writeOnly {
if packetsSent >= settings.maxPackets {
Log.logger.debug("stopping because packetsSent >= settings.maxPackets")
break
}
} else {
if packetsSent >= settings.maxPackets && packetsReceived >= settings.maxPackets {
Log.logger.debug("stopping because packetsSent >= settings.maxPackets && packetsReceived >= settings.maxPackets")
break
}
}
}
if hasTimeout {
stop()
}
Log.logger.debug("UDP AFTER SEND RETURNS \(!hasTimeout)")
return !hasTimeout
}
///
fileprivate func receivePacket(_ dataReceived: Data, fromAddress address: Data) { // TODO: use dataReceived
if packetsReceived < settings.maxPackets {
packetsReceived += 1
// call callback
settings.delegateQueue.async {
let _ = self.delegate?.udpStreamSender(self, didReceivePacket: dataReceived)
return
}
}
}
}
// MARK: GCDAsyncUdpSocketDelegate methods
///
extension UDPStreamSender: GCDAsyncUdpSocketDelegate {
///
func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) {
Log.logger.debug("didConnectToAddress: address: \(address)")
Log.logger.debug("didConnectToAddress: local port: \(self.udpSocket?.localPort() ?? 0)")
settings.delegateQueue.async {
self.delegate?.udpStreamSender(self, didBindToPort: self.udpSocket?.localPort() ?? 0)
return
}
countDownLatch.countDown()
}
///
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) {
Log.logger.debug("didNotConnect: \(String(describing: error))")
}
///
func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) {
// Log.logger.debug("didSendDataWithTag: \(tag)")
}
///
func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) {
Log.logger.debug("didNotSendDataWithTag: \(String(describing: error))")
}
///
func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
// Log.logger.debug("didReceiveData: \(data)")
// dispatch_async(streamSenderQueue) {
if self.running.boolValue {
self.receivePacket(data, fromAddress: address)
}
// }
}
///
func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { // crashes if NSError is used without questionmark
Log.logger.debug("udpSocketDidClose: \(String(describing: error))")
settings.delegateQueue.async {
self.delegate?.udpStreamSenderDidClose(self, with: error)
return
}
}
}
| apache-2.0 | 6c4df32fb1c05bf4b839ecf2d806866a | 28.670846 | 151 | 0.569995 | 4.99736 | false | false | false | false |
irealme/MapManager | MapManager.swift | 1 | 20432 | //
// MapManager.swift
//
//
// Created by Jimmy Jose on 14/08/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreLocation
import MapKit
typealias DirectionsCompletionHandler = ((route:MKPolyline?, directionInformation:NSDictionary?, boundingRegion:MKMapRect?, error:String?)->())?
// TODO: Documentation
class MapManager: NSObject{
private var directionsCompletionHandler:DirectionsCompletionHandler
private let errorNoRoutesAvailable = "No routes available"// add more error handling
private let errorDictionary = ["NOT_FOUND" : "At least one of the locations specified in the request's origin, destination, or waypoints could not be geocoded",
"ZERO_RESULTS":"No route could be found between the origin and destination",
"MAX_WAYPOINTS_EXCEEDED":"Too many waypointss were provided in the request The maximum allowed waypoints is 8, plus the origin, and destination",
"INVALID_REQUEST":"The provided request was invalid. Common causes of this status include an invalid parameter or parameter value",
"OVER_QUERY_LIMIT":"Service has received too many requests from your application within the allowed time period",
"REQUEST_DENIED":"Service denied use of the directions service by your application",
"UNKNOWN_ERROR":"Directions request could not be processed due to a server error. Please try again"]
override init(){
super.init()
}
func directions(#from:CLLocationCoordinate2D,to:NSString,directionCompletionHandler:DirectionsCompletionHandler){
self.directionsCompletionHandler = directionCompletionHandler
var geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(to as String, completionHandler: { (placemarksObject, error) -> Void in
if(error != nil){
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription)
}else{
var placemarks = placemarksObject as NSArray
var placemark = placemarks.lastObject as! CLPlacemark
var placemarkSource = MKPlacemark(coordinate: from, addressDictionary: nil)
var source = MKMapItem(placemark: placemarkSource)
var placemarkDestination = MKPlacemark(placemark: placemark)
var destination = MKMapItem(placemark: placemarkDestination)
self.directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler)
}
})
}
func directionsFromCurrentLocation(#to:NSString,directionCompletionHandler:DirectionsCompletionHandler){
self.directionsCompletionHandler = directionCompletionHandler
var geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(to as String, completionHandler: { (placemarksObject, error) -> Void in
if(error != nil){
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription)
}else{
var placemarks = placemarksObject as NSArray
var placemark = placemarks.lastObject as! CLPlacemark
var source = MKMapItem.mapItemForCurrentLocation()
var placemarkDestination = MKPlacemark(placemark: placemark)
var destination = MKMapItem(placemark: placemarkDestination)
self.directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler)
}
})
}
func directionsFromCurrentLocation(#to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){
var directionRequest = MKDirectionsRequest()
var source = MKMapItem.mapItemForCurrentLocation()
var placemarkDestination = MKPlacemark(coordinate: to, addressDictionary: nil)
var destination = MKMapItem(placemark: placemarkDestination)
directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler)
}
func directions(#from:CLLocationCoordinate2D, to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){
var directionRequest = MKDirectionsRequest()
var placemarkSource = MKPlacemark(coordinate: from, addressDictionary: nil)
var source = MKMapItem(placemark: placemarkSource)
var placemarkDestination = MKPlacemark(coordinate: to, addressDictionary: nil)
var destination = MKMapItem(placemark: placemarkDestination)
directionsFor(source: source, destination: destination, directionCompletionHandler: directionCompletionHandler)
}
private func directionsFor(#source:MKMapItem, destination:MKMapItem,directionCompletionHandler:DirectionsCompletionHandler){
self.directionsCompletionHandler = directionCompletionHandler
var directionRequest = MKDirectionsRequest()
directionRequest.setSource(source)
directionRequest.setDestination(destination)
directionRequest.transportType = MKDirectionsTransportType.Any
directionRequest.requestsAlternateRoutes = true
var directions = MKDirections(request: directionRequest)
directions.calculateDirectionsWithCompletionHandler({
(response:MKDirectionsResponse!, error:NSError!) -> Void in
if (error != nil) {
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription)
}else if(response.routes.isEmpty){
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: self.errorNoRoutesAvailable)
}else{
let route: MKRoute = response.routes[0] as! MKRoute
let steps = route.steps as NSArray
var stop = false
var end_address = route.name
var distance = route.distance.description
var duration = route.expectedTravelTime.description
var source = response.source.placemark.coordinate
var destination = response.destination.placemark.coordinate
var start_location = ["lat":source.latitude,"lng":source.longitude]
var end_location = ["lat":destination.latitude,"lng":destination.longitude]
var stepsFinalArray = NSMutableArray()
steps.enumerateObjectsUsingBlock({ (obj, idx, stop) -> Void in
var step:MKRouteStep = obj as! MKRouteStep
var distance = step.distance.description
var instructions = step.instructions
var stepsDictionary = NSMutableDictionary()
stepsDictionary.setObject(distance, forKey: "distance")
stepsDictionary.setObject("", forKey: "duration")
stepsDictionary.setObject(instructions, forKey: "instructions")
stepsFinalArray.addObject(stepsDictionary)
})
var stepsDict = NSMutableDictionary()
stepsDict.setObject(distance, forKey: "distance")
stepsDict.setObject(duration, forKey: "duration")
stepsDict.setObject(end_address, forKey: "end_address")
stepsDict.setObject(end_location, forKey: "end_location")
stepsDict.setObject("", forKey: "start_address")
stepsDict.setObject(start_location, forKey: "start_location")
stepsDict.setObject(stepsFinalArray, forKey: "steps")
self.directionsCompletionHandler!(route: route.polyline,directionInformation: stepsDict, boundingRegion: route.polyline.boundingMapRect, error: nil)
}
})
}
/**
Get directions using Google API by passing source and destination as string.
:param: from Starting point of journey
:param: to Ending point of journey
:returns: directionCompletionHandler: Completion handler contains polyline,dictionary,maprect and error
*/
func directionsUsingGoogle(#from:NSString, to:NSString,directionCompletionHandler:DirectionsCompletionHandler){
getDirectionsUsingGoogle(origin: from, destination: to, directionCompletionHandler: directionCompletionHandler)
}
func directionsUsingGoogle(#from:CLLocationCoordinate2D, to:CLLocationCoordinate2D,directionCompletionHandler:DirectionsCompletionHandler){
var originLatLng = "\(from.latitude),\(from.longitude)"
var destinationLatLng = "\(to.latitude),\(to.longitude)"
getDirectionsUsingGoogle(origin: originLatLng, destination: destinationLatLng, directionCompletionHandler: directionCompletionHandler)
}
func directionsUsingGoogle(#from:CLLocationCoordinate2D, to:NSString,directionCompletionHandler:DirectionsCompletionHandler){
var originLatLng = "\(from.latitude),\(from.longitude)"
getDirectionsUsingGoogle(origin: originLatLng, destination: to, directionCompletionHandler: directionCompletionHandler)
}
private func getDirectionsUsingGoogle(#origin:NSString, destination:NSString,directionCompletionHandler:DirectionsCompletionHandler){
self.directionsCompletionHandler = directionCompletionHandler
var path = "http://maps.googleapis.com/maps/api/directions/json?origin=\(origin)&destination=\(destination)"
performOperationForURL(path)
}
private func performOperationForURL(urlString:NSString){
let urlEncoded = urlString.stringByReplacingOccurrencesOfString(" ", withString: "%20")
let url:NSURL? = NSURL(string:urlEncoded)
let request:NSURLRequest = NSURLRequest(URL:url!)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in
if(error != nil){
println(error.localizedDescription)
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: error.localizedDescription)
}else{
let dataAsString: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
var err: NSError
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
let routes = jsonResult.objectForKey("routes") as! NSArray
let status = jsonResult.objectForKey("status") as! NSString
let route = routes.lastObject as! NSDictionary //first object?
if(status.isEqualToString("OK") && route.allKeys.count>0){
let legs = route.objectForKey("legs") as! NSArray
let steps = legs.firstObject as! NSDictionary
let directionInformation = self.parser(steps) as NSDictionary
let overviewPolyline = route.objectForKey("overview_polyline") as! NSDictionary
let points = overviewPolyline.objectForKey("points") as! NSString
var locations = self.decodePolyLine(points) as Array
var coordinates = locations.map({ (location: CLLocation) ->
CLLocationCoordinate2D in
return location.coordinate
})
var polyline = MKPolyline(coordinates: &coordinates,
count: locations.count)
self.directionsCompletionHandler!(route: polyline,directionInformation:directionInformation, boundingRegion: polyline.boundingMapRect, error: nil)
}else{
var errorMsg = self.errorDictionary[status as String]
if(errorMsg == nil){
errorMsg = self.errorNoRoutesAvailable
}
self.directionsCompletionHandler!(route: nil,directionInformation:nil, boundingRegion: nil, error: errorMsg)
}
}
}
)
}
private func decodePolyLine(encodedStr:NSString)->Array<CLLocation>{
var array = Array<CLLocation>()
let len = encodedStr.length
var range = NSMakeRange(0, len)
var strpolyline = encodedStr
var index = 0
var lat = 0 as Int32
var lng = 0 as Int32
strpolyline = encodedStr.stringByReplacingOccurrencesOfString("\\\\", withString: "\\", options: NSStringCompareOptions.LiteralSearch, range: range)
while(index<len){
var b = 0
var shift = 0
var result = 0
do{
var numUnichar = strpolyline.characterAtIndex(index++)
var num = NSNumber(unsignedShort: numUnichar)
var numInt = num.integerValue
b = numInt - 63
result |= (b & 0x1f) << shift
shift += 5
}while(b >= 0x20)
var dlat = 0
if((result & 1) == 1){
dlat = ~(result >> 1)
}else{
dlat = (result >> 1)
}
lat += dlat
shift = 0
result = 0
do{
var numUnichar = strpolyline.characterAtIndex(index++)
var num = NSNumber(unsignedShort: numUnichar)
var numInt = num.integerValue
b = numInt - 63
result |= (b & 0x1f) << shift
shift += 5
}while(b >= 0x20)
var dlng = 0
if((result & 1) == 1){
dlng = ~(result >> 1)
}else{
dlng = (result >> 1)
}
lng += dlng
var latitude = NSNumber(int:lat).doubleValue * 1e-5
var longitude = NSNumber(int:lng).doubleValue * 1e-5
var location = CLLocation(latitude: latitude, longitude: longitude)
array.append(location)
}
return array
}
private func parser(data:NSDictionary)->NSDictionary{
var dict = NSMutableDictionary()
var distance = (data.objectForKey("distance") as! NSDictionary).objectForKey("text") as! NSString
var duration = (data.objectForKey("duration") as! NSDictionary).objectForKey("text") as! NSString
var end_address = data.objectForKey("end_address") as! NSString
var end_location = data.objectForKey("end_location") as! NSDictionary
var start_address = data.objectForKey("start_address") as! NSString
var start_location = data.objectForKey("start_location") as! NSDictionary
var stepsArray = data.objectForKey("steps") as! NSArray
var stepsDict = NSMutableDictionary()
var stop = false
var stepsFinalArray = NSMutableArray()
stepsArray.enumerateObjectsUsingBlock { (obj, idx, stop) -> Void in
var stepDict = obj as! NSDictionary
var distance = (stepDict.objectForKey("distance") as! NSDictionary).objectForKey("text") as! NSString
var duration = (stepDict.objectForKey("duration") as! NSDictionary).objectForKey("text") as! NSString
var html_instructions = stepDict.objectForKey("html_instructions") as! NSString
var end_location = stepDict.objectForKey("end_location") as! NSDictionary
var instructions = self.removeHTMLTags((stepDict.objectForKey("html_instructions") as! NSString))
var start_location = stepDict.objectForKey("start_location") as! NSDictionary
var stepsDictionary = NSMutableDictionary()
stepsDictionary.setObject(distance, forKey: "distance")
stepsDictionary.setObject(duration, forKey: "duration")
stepsDictionary.setObject(html_instructions, forKey: "html_instructions")
stepsDictionary.setObject(end_location, forKey: "end_location")
stepsDictionary.setObject(instructions, forKey: "instructions")
stepsDictionary.setObject(start_location, forKey: "start_location")
stepsFinalArray.addObject(stepsDictionary)
}
stepsDict.setObject(distance, forKey: "distance")
stepsDict.setObject(duration, forKey: "duration")
stepsDict.setObject(end_address, forKey: "end_address")
stepsDict.setObject(end_location, forKey: "end_location")
stepsDict.setObject(start_address, forKey: "start_address")
stepsDict.setObject(start_location, forKey: "start_location")
stepsDict.setObject(stepsFinalArray, forKey: "steps")
return stepsDict
}
private func removeHTMLTags(source:NSString)->NSString{
var range = NSMakeRange(0, 0)
let HTMLTags = "<[^>]*>"
var sourceString = source
while( sourceString.rangeOfString(HTMLTags, options: NSStringCompareOptions.RegularExpressionSearch).location != NSNotFound){
range = sourceString.rangeOfString(HTMLTags, options: NSStringCompareOptions.RegularExpressionSearch)
sourceString = sourceString.stringByReplacingCharactersInRange(range, withString: "")
}
return sourceString;
}
}
| mit | 967c107316dbf6d0b52f702e71c58202 | 41.302277 | 169 | 0.600724 | 6.020035 | false | false | false | false |
davidbutz/ChristmasFamDuels | iOS/Boat Aware/RangeSliderTrackLayer.swift | 1 | 2312 | //
// RangeSliderTrackLayer.swift
// Boat Aware
//
// Created by Dave Butz on 6/1/16.
// Copyright © 2016 Thrive Engineering. All rights reserved.
//
import UIKit
import QuartzCore
class RangeSliderTrackLayer: CALayer {
weak var rangeSlider: RangeSlider?
override func drawInContext(ctx: CGContext) {
if let slider = rangeSlider {
// Clip
let cornerRadius = bounds.height * slider.curvaceousness / 2.0
let path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius)
CGContextAddPath(ctx, path.CGPath)
// Fill the track
CGContextSetFillColorWithColor(ctx, slider.trackTintColor.CGColor)
CGContextAddPath(ctx, path.CGPath)
CGContextFillPath(ctx)
// Fill the highlighted range
CGContextSetFillColorWithColor(ctx, slider.trackHighlightYellowColor.CGColor)
let lowerValuePosition = CGFloat(slider.positionForValue(slider.firstValue))
let upperValuePosition = CGFloat(slider.positionForValue(slider.secondValue))
let rect = CGRect(x: lowerValuePosition, y: 0.0, width: upperValuePosition - lowerValuePosition, height: bounds.height)
CGContextFillRect(ctx, rect)
CGContextSetFillColorWithColor(ctx, slider.trackHighlightGreenColor.CGColor)
let lowerValuePosition2 = CGFloat(slider.positionForValue(slider.secondValue))
let upperValuePosition2 = CGFloat(slider.positionForValue(slider.thirdValue))
let rect2 = CGRect(x: lowerValuePosition2, y: 0.0, width: upperValuePosition2 - lowerValuePosition2, height: bounds.height)
CGContextFillRect(ctx, rect2)
CGContextSetFillColorWithColor(ctx, slider.trackHighlightYellowColor.CGColor)
let lowerValuePosition3 = CGFloat(slider.positionForValue(slider.thirdValue))
let upperValuePosition3 = CGFloat(slider.positionForValue(slider.fourthValue))
let rect3 = CGRect(x: lowerValuePosition3, y: 0.0, width: upperValuePosition3 - lowerValuePosition3, height: bounds.height)
CGContextFillRect(ctx, rect3)
}
}
}
| mit | fef8b135b99be69ba1a6eb36477ef54f | 41.018182 | 135 | 0.656859 | 5.300459 | false | false | false | false |
jatoben/RocksDB | Sources/DBIterator.swift | 1 | 2129 | /*
* DBIterator.swift
* Copyright (c) 2016 Ben Gollmer.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import CRocksDB
public class DBIterator: IteratorProtocol {
private var iter: OpaquePointer
fileprivate init(_ iter: OpaquePointer, _ keyPrefix: String? = nil) {
self.iter = iter
if let prefix = keyPrefix {
rocksdb_iter_seek(iter, prefix, prefix.utf8.count)
} else {
rocksdb_iter_seek_to_first(self.iter)
}
}
deinit {
rocksdb_iter_destroy(iter)
}
public func next() -> (DBEntry, DBEntry)? {
guard rocksdb_iter_valid(iter) != 0 else { return nil }
var keyLength: Int = 0
var valLength: Int = 0
let k = rocksdb_iter_key(iter, &keyLength)
let v = rocksdb_iter_value(iter, &valLength)
guard let key = k, let val = v else { return nil }
defer { rocksdb_iter_next(iter) }
let keyPointer = UnsafeBufferPointer(start: key, count: keyLength)
let valPointer = UnsafeBufferPointer(start: val, count: valLength)
return (DBEntry(dbValue: [Int8](keyPointer)), DBEntry(dbValue: [Int8](valPointer)))
}
}
extension Database: Sequence {
public func makeIterator(_ opts: DBReadOptions, keyPrefix prefix: String? = nil) -> DBIterator {
let i = rocksdb_create_iterator(db, opts.opts)
guard let iter = i else { preconditionFailure("Could not create database iterator") }
return DBIterator(iter, prefix)
}
public func makeIterator(keyPrefix prefix: String) -> DBIterator {
return makeIterator(readOptions, keyPrefix: prefix)
}
public func makeIterator() -> DBIterator {
return makeIterator(readOptions)
}
}
| apache-2.0 | 11702a2b687b0fb87ace585ad0094733 | 30.776119 | 98 | 0.699389 | 3.808587 | false | false | false | false |
killerpsyco/Parameter-Calculator-of-Transistor | TFT Performance/PerformanceCalculator.swift | 1 | 1359 | //
// PerformanceCalculator.swift
// TFT Performance
//
// Created by dyx on 15/6/16.
// Copyright (c) 2015年 dyx. All rights reserved.
//
import Foundation
class PerformanceCalculator {
func sqrtGradient(cu1: Double, cu2: Double, voltage1: Double, voltage2: Double) -> Double? {
let sqrtCu1 = sqrt(cu1)
let sqrtCu2 = sqrt(cu2)
return (sqrtCu2 - sqrtCu1) / (voltage2 - voltage1)
}
func thresholdVoltage(cu1: Double, voltage1: Double, gradient: Double) -> Double? {
let sqrtCu1 = sqrt(cu1)
let intercept = sqrtCu1 - gradient * voltage1
if gradient != 0 {
let thVoltage = -(intercept / gradient)
println("\(thVoltage)")
return thVoltage
}
else {
return 0.0
}
}
func mobility(length: Double, width: Double, capacity: Double, gradient: Double) -> Double? {
return 2 * (length * 1e-6) * (gradient * gradient * 1e-6) * 1e4 / (width * 1e-2 * capacity * 1e-5)
}
func onOffRatio(Ion: Double, Ioff: Double) -> Double {
return Ion / Ioff
}
func thresholdSwing(cu1: Double, cu2: Double, voltage1: Double, voltage2: Double) -> Double? {
let log1 = log10(cu1)
let log2 = log10(cu2)
return (voltage1 - voltage2) / (log1 - log2)
}
}
| epl-1.0 | 509bc58e166859d2c8263b3f339ef3c5 | 27.87234 | 106 | 0.574797 | 3.426768 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/BitcoinChainKit/Transactions/Bitcoin/BTCOnChainTxEngineState.swift | 1 | 778 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
struct BTCOnChainTxEngineState<Token: BitcoinChainToken> {
private(set) var transactionCandidate: NativeBitcoinTransactionCandidate?
private(set) var context: NativeBitcoinTransactionContext?
init(
transactionCandidate: NativeBitcoinTransactionCandidate? = nil,
context: NativeBitcoinTransactionContext? = nil
) {
self.transactionCandidate = transactionCandidate
self.context = context
}
mutating func add(transactionCandidate: NativeBitcoinTransactionCandidate) {
self.transactionCandidate = transactionCandidate
}
mutating func add(context: NativeBitcoinTransactionContext) {
self.context = context
}
}
| lgpl-3.0 | 0452f5418bd4307ca00da18c98559c67 | 28.884615 | 80 | 0.743887 | 5.078431 | false | false | false | false |
kosicki123/WWDC | WWDC/PreferencesWindowController.swift | 1 | 4901 | //
// PreferencesWindowController.swift
// WWDC
//
// Created by Guilherme Rambo on 01/05/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
class PreferencesWindowController: NSWindowController {
let prefs = Preferences.SharedPreferences()
convenience init() {
self.init(windowNibName: "PreferencesWindowController")
}
@IBOutlet weak var downloadProgressIndicator: NSProgressIndicator!
override func windowDidLoad() {
super.windowDidLoad()
populateFontsPopup()
downloadsFolderLabel.stringValue = prefs.localVideoStoragePath
automaticRefreshEnabledCheckbox.state = prefs.automaticRefreshEnabled ? NSOnState : NSOffState
if let familyName = prefs.transcriptFont.familyName {
fontPopUp.selectItemWithTitle(familyName)
}
let size = "\(Int(prefs.transcriptFont.pointSize))"
sizePopUp.selectItemWithTitle(size)
textColorWell.color = prefs.transcriptTextColor
bgColorWell.color = prefs.transcriptBgColor
}
// MARK: Downloads folder
@IBOutlet weak var downloadsFolderLabel: NSTextField!
@IBAction func changeDownloadsFolder(sender: NSButton) {
let panel = NSOpenPanel()
panel.directoryURL = NSURL(fileURLWithPath: Preferences.SharedPreferences().localVideoStoragePath)
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.canCreateDirectories = true
panel.prompt = "Choose"
panel.beginSheetModalForWindow(window!) { result in
if result > 0 {
if let path = panel.URL?.path {
Preferences.SharedPreferences().localVideoStoragePath = path
self.downloadsFolderLabel.stringValue = path
}
}
}
}
@IBAction func downloadAllSessions(sender: AnyObject) {
let completionHandler: DataStore.fetchSessionsCompletionHandler = { success, sessions in
dispatch_async(dispatch_get_main_queue()) {
let sessions2015 = sessions.filter{(session) in
return session.year == 2015 && !VideoStore.SharedStore().hasVideo(session.hd_url!)
}
println("Videos fetched, start downloading")
DownloadVideosBatch.SharedDownloader().sessions = sessions2015
DownloadVideosBatch.SharedDownloader().startDownloading()
}
}
DataStore.SharedStore.fetchSessions(completionHandler, disableCache: true)
if let appDelegate = NSApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.showDownloadsWindow(appDelegate)
}
}
@IBAction func revealInFinder(sender: NSButton) {
let path = Preferences.SharedPreferences().localVideoStoragePath
let root = path.stringByDeletingLastPathComponent
NSWorkspace.sharedWorkspace().selectFile(path, inFileViewerRootedAtPath: root)
}
// MARK: Session refresh
@IBOutlet weak var automaticRefreshEnabledCheckbox: NSButton!
@IBAction func automaticRefreshCheckboxAction(sender: NSButton) {
prefs.automaticRefreshEnabled = (sender.state == NSOnState)
}
// MARK: Transcript appearance
@IBOutlet weak var fontPopUp: NSPopUpButton!
@IBOutlet weak var sizePopUp: NSPopUpButton!
@IBOutlet weak var textColorWell: NSColorWell!
@IBOutlet weak var bgColorWell: NSColorWell!
@IBAction func fontPopUpAction(sender: NSPopUpButton) {
if let newFont = NSFont(name: fontPopUp.selectedItem!.title, size: prefs.transcriptFont.pointSize) {
prefs.transcriptFont = newFont
}
}
@IBAction func sizePopUpAction(sender: NSPopUpButton) {
let size = NSString(string: sizePopUp.selectedItem!.title).doubleValue
prefs.transcriptFont = NSFont(name: prefs.transcriptFont.fontName, size: CGFloat(size))!
}
@IBAction func textColorWellAction(sender: NSColorWell) {
prefs.transcriptTextColor = textColorWell.color
}
@IBAction func bgColorWellAction(sender: NSColorWell) {
prefs.transcriptBgColor = bgColorWell.color
}
func populateFontsPopup() {
fontPopUp.addItemsWithTitles(NSFontManager.sharedFontManager().availableFontFamilies)
}
private func hideProgressIndicator() {
self.downloadProgressIndicator.hidden = true
downloadProgressIndicator.stopAnimation(nil)
}
private func showProgressIndicator() {
self.downloadProgressIndicator.hidden = false
downloadProgressIndicator.startAnimation(nil)
}
}
| bsd-2-clause | c8be82cab0cfd20d40aa2e14d5d240ca | 32.568493 | 108 | 0.653132 | 5.834524 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Category/Extension/UIToolbar + Extension.swift | 1 | 1091 | //
// UIToolbar + Extension.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/30.
// Copyright © 2016年 CoderST. All rights reserved.
//
import Foundation
import UIKit
extension UIToolbar {
/// 隐藏头部线
func hideHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = true
}
/// 显示头部线
func showHairline() {
let navigationBarImageView = hairlineImageViewInToolbar(view: self)
navigationBarImageView!.isHidden = false
}
/// 实现方法
private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? {
if view.isKind(of : UIImageView.self) && view.bounds.height <= 1.0 {
return (view as! UIImageView)
}
let subviews = (view.subviews as [UIView])
for subview: UIView in subviews {
if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) {
return imageView
}
}
return nil
}
}
| mit | f9745673464daa2374db1816da40dc3c | 24.238095 | 87 | 0.606604 | 4.549356 | false | false | false | false |
EurekaCommunity/GooglePlacesRow | Sources/GPTableViewCell.swift | 1 | 1132 | //
// GPTableViewCell.swift
// GooglePlacesRow
//
// Created by Mathias Claassen on 4/14/16.
//
//
import Foundation
import GooglePlaces
import Eureka
public protocol EurekaGooglePlacesTableViewCell {
func setTitle(_ prediction: GMSAutocompletePrediction)
}
/// Default cell for the table of the GooglePlacesTableCell
open class GPTableViewCell: UITableViewCell, EurekaGooglePlacesTableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initialize()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
func initialize() {
textLabel?.font = UIFont.systemFont(ofSize: 16)
textLabel?.minimumScaleFactor = 0.8
textLabel?.adjustsFontSizeToFitWidth = true
textLabel?.textColor = UIColor.blue
contentView.backgroundColor = UIColor.white
}
open func setTitle(_ prediction: GMSAutocompletePrediction) {
textLabel?.text = prediction.attributedFullText.string
}
}
| mit | f5806e8da313c270aee2e8bd5bb546e3 | 26.609756 | 79 | 0.70318 | 5.00885 | false | false | false | false |
mleiv/IBIncludedStoryboard | IBIncludedWrapperViewController.swift | 2 | 9490 | //
// IBIncludedWrapperViewController.swift
//
// Copyright 2015 Emily Ivie
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
//
import UIKit
//MARK: IBIncludedSegueableController protocol
public typealias PrepareAfterIBIncludedSegueType = (UIViewController) -> Bool
/**
Protocol to identify nested IBIncluded{Thing} view controllers that need to share data during prepareForSegue.
Note: This is not a default protocol applied to all IBIncluded{Thing} - you have to apply it individually to nibs/storyboards that are sharing data.
*/
@objc public protocol IBIncludedSegueableController {
/// Run code before segueing away or prepare for segue to a non-IBIncluded{Thing} page.
/// Do not use to share data (see prepareAfterIBIncludedSegue for that).
/// - parameter segue: The segue object containing information about the view controllers involved in the segue. See [prepareForSegue documentation](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/prepareForSegue:sender:)
/// - parameter sender: The object that initiated the segue. You might use this parameter to perform different actions based on which control (or other object) initiated the segue. See [prepareForSegue documentation](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/occ/instm/UIViewController/prepareForSegue:sender:)
/// - returns: `true` if function has finished its work and can be deleted, `false` if it did not find the controller it is looking for yet.
optional func prepareBeforeIBIncludedSegue(segue: UIStoryboardSegue, sender: AnyObject?) -> Bool
/// Check the destination view controller type and share data if it is what you want.
optional var prepareAfterIBIncludedSegue: PrepareAfterIBIncludedSegueType { get set }
}
//MARK: IBIncludedWrapperViewController definition
/**
Forwards any prepareForSegue behavior between nested IBIncluded{Thing} view controllers.
Runs for all nested IBIncludedWrapperViewControllers, so you can have some pretty intricately-nested levels of stroyboards/nibs and they can still share data, so long as a segue is involved.
Assign this class to all IBIncluded{Thing} placeholder/wrapper view controllers involved at any level in sharing data between controllers.
*/
public class IBIncludedWrapperViewController: UIViewController, IBIncludedSegueableWrapper {
internal var includedViewControllers = [IBIncludedSegueableController]()
internal var prepareAfterSegueClosures:[PrepareAfterIBIncludedSegueType] = []
/**
Forward any segues to the saved included view controllers.
(Also, save any of their prepareAfterIBIncludedSegue closures for the destination to process -after- IBIncluded{Thing} is included.)
Can handle scenarios where one half of the segue in an IBIncluded{Thing} but the other half isn't.
*/
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//super.prepareForSegue(segue, sender: sender) //doesn't help propogate up the segue
forwardToParentControllers(segue, sender: sender)
// forward for pre-segue preparations:
for includedController in includedViewControllers {
includedController.prepareBeforeIBIncludedSegue?(segue, sender: sender)
}
// save/share post-segue closures for later execution:
// skip any navigation/tab controllers
if let destinationController = activeViewController(segue.destinationViewController) {
tryToApplyClosures(destinationController)
}
prepareAfterSegueClosures = [] // we are done, clean up any lingering controllers in case we have ARC issues
// NOTE: you may not want this if you are doing very delayed prepareAfterSegue stuff (like, delayed until after a segue to another page and coming back), but I have seen no ill effects myself.
}
public func tryToApplyClosures(destinationController: UIViewController?) {
if let includedDestination = destinationController as? IBIncludedWrapperViewController {
// check self for any seguable closures (if we aren't IBIncluded{Thing} but are segueing to one):
if let selfSegue = self as? IBIncludedSegueableController, let closure = selfSegue.prepareAfterIBIncludedSegue {
includedDestination.prepareAfterSegueClosures.append(closure)
}
// check all seguable closures now:
for includedController in includedViewControllers {
if let closure = includedController.prepareAfterIBIncludedSegue {
includedDestination.prepareAfterSegueClosures.append(closure)
}
}
if includedDestination is IBIncludedSegueableController {
// it's a seguable controller also, so run all seguable closures now:
for includedController in includedViewControllers {
if let closure = includedController.prepareAfterIBIncludedSegue {
closure(destinationController!) //nil already tested above
}
}
}
// execute now on top-level destination (if we are segueing from IBIncluded{Thing} to something that is not):
} else if destinationController != nil {
// check self for any seguable closures (if we aren't IBIncluded{Thing} but are segueing to one):
if let selfSegue = self as? IBIncludedSegueableController {
if let closure = selfSegue.prepareAfterIBIncludedSegue {
closure(destinationController!)
}
}
// check all seguable closures now:
for includedController in includedViewControllers {
if let closure = includedController.prepareAfterIBIncludedSegue {
closure(destinationController!)
}
}
}
}
/**
Save any included view controllers that may need segue handling later.
*/
public func addIncludedViewController(viewController: UIViewController) {
// skip any navigation/tab controllers
if let newController = activeViewController(viewController) where newController != viewController {
return addIncludedViewController(newController)
}
// only save segue-handling controllers
if let includedController = viewController as? IBIncludedSegueableController {
includedViewControllers.append(includedController)
}
// try running saved segue closures, delete any that are marked finished
prepareAfterSegueClosures = prepareAfterSegueClosures.filter { closure in
let finished = closure(viewController)
return !finished
}
}
public func addClosure(newClosure: PrepareAfterIBIncludedSegueType) {
prepareAfterSegueClosures.append(newClosure)
}
public func resetClosures() {
prepareAfterSegueClosures = []
}
/**
Propogates the segue up to parent IBIncludedWrapperViewControllers so they can also run the prepareAfterIBIncludedSegue() on their included things.
Since any IBIncluded{Thing} attaches to all IBIncludedWrapperViewControllers in the hierarchy, I am not sure why this is required, but I know the prior version didn't work in some heavily-nested scenarios without this addition.
:param: controller (optional) view controller to start looking under, defaults to window's rootViewController
:returns: an (optional) view controller
*/
private func forwardToParentControllers(segue: UIStoryboardSegue, sender: AnyObject?) {
var currentController = self as UIViewController
while let controller = currentController.parentViewController {
if let wrapperController = controller as? IBIncludedWrapperViewController {
wrapperController.prepareForSegue(segue, sender: sender)
break //wrapperController will do further parents
}
currentController = controller
}
}
/**
Locates the top-most view controller that is under the tab/nav controllers
:param: controller (optional) view controller to start looking under, defaults to window's rootViewController
:returns: an (optional) view controller
*/
private func activeViewController(controller: UIViewController!) -> UIViewController? {
if controller == nil {
return nil
}
if let tabController = controller as? UITabBarController, let nextController = tabController.selectedViewController {
return activeViewController(nextController)
} else if let navController = controller as? UINavigationController, let nextController = navController.visibleViewController {
return activeViewController(nextController)
} else if let nextController = controller.presentedViewController {
return activeViewController(nextController)
}
return controller
}
}
| mit | 40d2614e0597c0e698f17a7eeb236b87 | 51.722222 | 389 | 0.707482 | 5.976071 | false | false | false | false |
boolkybear/SwiftAsyncGraph | AsyncGraphDemo/AsyncGraphDemoTests/AsyncGraphDemoTests.swift | 1 | 7467 | //
// AsyncGraphDemoTests.swift
// AsyncGraphDemoTests
//
// Created by Boolky Bear on 2/12/14.
// Copyright (c) 2014 ByBDesigns. All rights reserved.
//
import UIKit
import XCTest
struct NodeIdentifier
{
let identifier: String
let tag: Int?
init (_ identifier: String, _ tag: Int? = nil)
{
self.identifier = identifier
self.tag = tag
}
func toString() -> String {
let tagStr = self.tag.map { "\($0)" } ?? "null"
return "\(self.identifier) - \(tagStr)"
}
var hashValue: Int {
return self.toString().hashValue
}
}
func == (lhs: NodeIdentifier, rhs: NodeIdentifier) -> Bool {
return lhs.identifier == rhs.identifier && lhs.tag == rhs.tag
}
class AsyncGraphDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// func testExample() {
// // This is an example of a functional test case.
// XCTAssert(true, "Pass")
// }
//
// func testPerformanceExample() {
// // This is an example of a performance test case.
// self.measureBlock() {
// // Put the code you want to measure the time of here.
// }
// }
func testNodeIdentifiers()
{
let node1nil = NodeIdentifier("one")
let node1tag = NodeIdentifier("one", 1)
let node2nil = NodeIdentifier("two")
let node2tag = NodeIdentifier("two", 1)
let other1nil = NodeIdentifier("one")
let other1tag1 = NodeIdentifier("one", 1)
let other1tag2 = NodeIdentifier("one", 2)
XCTAssertFalse(node1nil == node1tag, "Nodes with different tags should not be equal")
XCTAssertFalse(node1nil == node2nil, "Nodes with different identifiers should not be equal")
XCTAssertFalse(node1tag == node2tag, "Nodes with different identifiers should not be equal, even tag is equal")
XCTAssert(node1nil == other1nil, "Nodes with same identifier and same tag should be equal")
XCTAssert(node1tag == other1tag1, "Nodes with same identifier and same tag should be equal")
XCTAssertFalse(node1tag == other1tag2, "Nodes with different tags should not be equal, even identifier is equal")
}
func testTwoIndependentItems()
{
let times: [ String : NSTimeInterval ] = [ "first" : 0.5,
"second" : 1.0, ]
var finishOrder = [String]()
AsyncGraph<String, Void> {
nodeIdentifier, operation, graph in
NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!))
finishOrder.append(nodeIdentifier)
}
.addNodeWithIdentifier("first")
.addNodeWithIdentifier("second")
.processSynchronous()
XCTAssertEqual(finishOrder, [ "first", "second" ], "Finish order should be first, second")
}
func testTwoDependentItems()
{
let times: [ String : NSTimeInterval ] = [ "first" : 0.5,
"second" : 1.0, ]
var finishOrder = [String]()
AsyncGraph<String, Void> {
nodeIdentifier, operation, graph in
NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!))
finishOrder.append(nodeIdentifier)
}
.addNodeWithIdentifier("first")
.addNodeWithIdentifier("second")
.addDependencyFrom("second", to: "first")
.processSynchronous()
XCTAssertEqual(finishOrder, [ "first", "second" ], "Finish order should be first, second")
}
func testTwoDependentItemsReversed()
{
let times: [ String : NSTimeInterval ] = [ "first" : 0.5,
"second" : 1.0, ]
var finishOrder = [String]()
AsyncGraph<String, Void> {
nodeIdentifier, operation, graph in
NSThread.sleepForTimeInterval(NSTimeInterval(times[nodeIdentifier]!))
finishOrder.append(nodeIdentifier)
}
.addNodeWithIdentifier("first")
.addNodeWithIdentifier("second")
.addDependencyFrom("first", to: "second")
.processSynchronous()
XCTAssertEqual(finishOrder, [ "second", "first" ], "Finish order should be second, first")
}
func testAsyncOperationGraph()
{
let graph = AsyncGraph<String, String?>()
var result = [ String ]()
graph.addNodeWithIdentifier("5") {
identifier, operation, graph in
NSThread.sleepForTimeInterval(5.0)
result.append(identifier)
return nil
}.addNodeWithIdentifier("3") {
identifier, operation, graph in
NSThread.sleepForTimeInterval(3.0)
result.append(identifier)
return nil
}.processSynchronous()
let resultString = result.joinWithSeparator("#")
XCTAssert(resultString == "3#5")
}
func testAsyncOperationGraphWithDependencies()
{
let graphWithDependencies = AsyncGraph<String, String?>()
var resultWithDependencies = [ String ]()
graphWithDependencies.addNodeWithIdentifier("5") {
identifier, operation, graph in
NSThread.sleepForTimeInterval(5.0)
resultWithDependencies.append(identifier)
return nil
}.addNodeWithIdentifier("3") {
identifier, operation, graph in
NSThread.sleepForTimeInterval(3.0)
resultWithDependencies.append(identifier)
return nil
}.addDependencyFrom("3", to: "5")
.processSynchronous()
let resultWithDependenciesString = resultWithDependencies.joinWithSeparator("#")
XCTAssert(resultWithDependenciesString == "5#3")
}
func testAsyncOperationGraphDefault()
{
var resultDefault = [ String ]()
let graphWithDefault = AsyncGraph<String, Void> {
identifier, operation, graph in
let timeInterval = NSTimeInterval(Int(identifier) ?? 0)
NSThread.sleepForTimeInterval(timeInterval)
resultDefault.append(identifier)
}
graphWithDefault.addNodeWithIdentifier("5")
.addNodeWithIdentifier("3")
.processSynchronous()
let resultDefaultString = resultDefault.joinWithSeparator("#")
XCTAssert(resultDefaultString == "3#5")
}
func testAsyncOperationHooks()
{
let graph = AsyncGraph<Int, String> {
identifier, operation, graph in
NSThread.sleepForTimeInterval(NSTimeInterval(identifier))
return "\(identifier)"
}
var isCompleted = false
var before = 0
var after = 0
let expectation = expectationWithDescription("Test graph")
graph.addNodeWithIdentifier(3)
.addNodeWithIdentifier(5)
.addHook {
graph in
expectation.fulfill()
isCompleted = true
}
.addHookBefore(3) {
identifier, operation, graph in
before += identifier
}
.addHookAfter(5) {
identifier, operation, graph in
after -= identifier
}
.process()
waitForExpectationsWithTimeout(10) { (error) in
XCTAssertNil(error, "\(error)")
}
XCTAssert(isCompleted, "Graph has not been completed")
XCTAssert(graph.resultFrom(3) == "3")
XCTAssert(graph.resultFrom(5) == "5")
XCTAssert(graph.status == .Processed)
XCTAssert(before == 3)
XCTAssert(after == -5)
}
func testCancel()
{
let graph = AsyncGraph<Int, String> {
identifier, operation, graph in
NSThread.sleepForTimeInterval(NSTimeInterval(identifier))
return "\(identifier)"
}
let expectation = expectationWithDescription("Test graph")
graph.addNodeWithIdentifier(3)
.addHook {
graph in
expectation.fulfill()
}
.process()
graph.cancel()
waitForExpectationsWithTimeout(10) { (error) in
XCTAssertNil(error, "\(error)")
}
XCTAssert(graph.status == .Cancelled)
}
}
| mit | 50c26cc6532ad7738f9c17439f418f7c | 24.226351 | 115 | 0.678854 | 3.848969 | false | true | false | false |
Antondomashnev/Sourcery | SourceryTests/Stub/Performance-Code/Kiosk/App/Models/BuyersPremium.swift | 4 | 454 | import UIKit
import SwiftyJSON
final class BuyersPremium: NSObject, JSONAbleType {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
static func fromJSON(_ json: [String: Any]) -> BuyersPremium {
let json = JSON(json)
let id = json["id"].stringValue
let name = json["name"].stringValue
return BuyersPremium(id: id, name: name)
}
}
| mit | 33d799c359d271989259c3459ba24e9b | 21.7 | 66 | 0.603524 | 4.017699 | false | false | false | false |
parrotbait/CorkWeather | CorkWeather/Source/UI/Localisation/LocalisedButton.swift | 1 | 1834 | //
// LocalisedButton.swift
// CorkWeather
//
// Created by Eddie Long on 09/01/2019.
// Copyright © 2019 eddielong. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
public class LocalisedButton : UIButton {
@IBInspectable public var normalText : String = ""
@IBInspectable public var highlightText : String = ""
@IBInspectable public var disabledText : String = ""
@IBInspectable public var selectedText : String = ""
@IBInspectable public var focusedText : String = ""
open override func layoutSubviews() {
super.layoutSubviews()
syncWithIB()
}
func syncWithIB() {
guard let localisedBundle = LanguageSelectorView.getBundle(object: self) else {
return
}
if !self.normalText.isEmpty {
let ret = localisedBundle.localizedString(forKey: self.normalText, value: "", table: nil)
setTitle(ret, for: .normal)
}
if !self.highlightText.isEmpty {
let ret = localisedBundle.localizedString(forKey: self.highlightText, value: "", table: nil)
setTitle(ret, for: .highlighted)
}
if !self.disabledText.isEmpty {
let ret = localisedBundle.localizedString(forKey: self.disabledText, value: "", table: nil)
setTitle(ret, for: .disabled)
}
if !self.selectedText.isEmpty {
let ret = localisedBundle.localizedString(forKey: self.selectedText, value: "", table: nil)
setTitle(ret, for: .selected)
}
if !self.focusedText.isEmpty {
let ret = localisedBundle.localizedString(forKey: self.focusedText, value: "", table: nil)
if #available(iOS 9.0, *) {
setTitle(ret, for: .focused)
}
}
}
}
| mit | 40169bc1b84ebd09244d5009d1737ac5 | 32.327273 | 104 | 0.608838 | 4.537129 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Login/LoginVerifyMobileViewController.swift | 1 | 7758 | //
// LoginVerifyMobileViewController.swift
// Yep
//
// Created by NIX on 15/3/17.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepNetworking
import YepKit
import Ruler
import RxSwift
import RxCocoa
final class LoginVerifyMobileViewController: UIViewController {
var mobile: String!
var areaCode: String!
private lazy var disposeBag = DisposeBag()
@IBOutlet private weak var verifyMobileNumberPromptLabel: UILabel!
@IBOutlet private weak var verifyMobileNumberPromptLabelTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var phoneNumberLabel: UILabel!
@IBOutlet private weak var verifyCodeTextField: BorderTextField!
@IBOutlet private weak var verifyCodeTextFieldTopConstraint: NSLayoutConstraint!
@IBOutlet private weak var callMePromptLabel: UILabel!
@IBOutlet private weak var callMeButton: UIButton!
@IBOutlet private weak var callMeButtonTopConstraint: NSLayoutConstraint!
private lazy var nextButton: UIBarButtonItem = {
let button = UIBarButtonItem()
button.title = NSLocalizedString("Next", comment: "")
button.rx_tap
.subscribeNext({ [weak self] in self?.login() })
.addDisposableTo(self.disposeBag)
return button
}()
private lazy var callMeTimer: NSTimer = {
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(LoginVerifyMobileViewController.tryCallMe(_:)), userInfo: nil, repeats: true)
return timer
}()
private var haveAppropriateInput = false {
didSet {
nextButton.enabled = haveAppropriateInput
if (oldValue != haveAppropriateInput) && haveAppropriateInput {
login()
}
}
}
private var callMeInSeconds = YepConfig.callMeInSeconds()
deinit {
callMeTimer.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
println("deinit LoginVerifyMobile")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.yepViewBackgroundColor()
navigationItem.titleView = NavigationTitleLabel(title: NSLocalizedString("Login", comment: ""))
navigationItem.rightBarButtonItem = nextButton
NSNotificationCenter.defaultCenter()
.rx_notification(AppDelegate.Notification.applicationDidBecomeActive)
.subscribeNext({ [weak self] _ in self?.verifyCodeTextField.becomeFirstResponder() })
.addDisposableTo(disposeBag)
verifyMobileNumberPromptLabel.text = NSLocalizedString("Input verification code sent to", comment: "")
phoneNumberLabel.text = "+" + areaCode + " " + mobile
verifyCodeTextField.placeholder = " "
verifyCodeTextField.backgroundColor = UIColor.whiteColor()
verifyCodeTextField.textColor = UIColor.yepInputTextColor()
verifyCodeTextField.rx_text
.map({ $0.characters.count == YepConfig.verifyCodeLength() })
.subscribeNext({ [weak self] in self?.haveAppropriateInput = $0 })
.addDisposableTo(disposeBag)
callMePromptLabel.text = NSLocalizedString("Didn't get it?", comment: "")
callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
verifyMobileNumberPromptLabelTopConstraint.constant = Ruler.iPhoneVertical(30, 50, 60, 60).value
verifyCodeTextFieldTopConstraint.constant = Ruler.iPhoneVertical(30, 40, 50, 50).value
callMeButtonTopConstraint.constant = Ruler.iPhoneVertical(10, 20, 40, 40).value
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
nextButton.enabled = false
callMeButton.enabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
verifyCodeTextField.becomeFirstResponder()
callMeTimer.fire()
}
// MARK: Actions
@objc private func tryCallMe(timer: NSTimer) {
if !haveAppropriateInput {
if callMeInSeconds > 1 {
let callMeInSecondsString = String.trans_buttonCallMe + " (\(callMeInSeconds))"
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(callMeInSecondsString, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
} else {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
}
callMeButton.enabled = true
}
}
if (callMeInSeconds > 1) {
callMeInSeconds -= 1
}
}
@IBAction private func callMe(sender: UIButton) {
callMeTimer.invalidate()
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCalling, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = false
}
delay(10) {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = true
}
}
sendVerifyCodeOfMobile(mobile, withAreaCode: areaCode, useMethod: .Call, failureHandler: { reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
if let errorMessage = errorMessage {
YepAlert.alertSorry(message: errorMessage, inViewController: self)
SafeDispatch.async {
UIView.performWithoutAnimation { [weak self] in
self?.callMeButton.setTitle(String.trans_buttonCallMe, forState: .Normal)
self?.callMeButton.layoutIfNeeded()
self?.callMeButton.enabled = true
}
}
}
}, completion: { success in
println("resendVoiceVerifyCode \(success)")
})
}
private func login() {
view.endEditing(true)
guard let verifyCode = verifyCodeTextField.text else {
return
}
YepHUD.showActivityIndicator()
loginByMobile(mobile, withAreaCode: areaCode, verifyCode: verifyCode, failureHandler: { [weak self] (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepHUD.hideActivityIndicator()
if let errorMessage = errorMessage {
SafeDispatch.async {
self?.nextButton.enabled = false
}
YepAlert.alertSorry(message: errorMessage, inViewController: self, withDismissAction: {
SafeDispatch.async {
self?.verifyCodeTextField.text = nil
self?.verifyCodeTextField.becomeFirstResponder()
}
})
}
}, completion: { loginUser in
println("loginUser: \(loginUser)")
YepHUD.hideActivityIndicator()
SafeDispatch.async {
saveTokenAndUserInfoOfLoginUser(loginUser)
syncMyInfoAndDoFurtherAction {
}
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
appDelegate.startMainStory()
}
}
})
}
}
| mit | 7ad37734b174fa8c3af380d828a49d3d | 32.431034 | 175 | 0.627256 | 5.461972 | false | false | false | false |
everald/JetPack | Sources/Experimental/TypeInstanceDictionary.swift | 2 | 2018 | public struct TypeInstanceDictionary {
fileprivate var instances = [ObjectIdentifier : Any]()
public init() {}
// Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to convert the instance type to a non-optional first.
public mutating func assign<T>(_ instance: T) {
assign(instance, toType: T.self)
}
public mutating func assign<T>(_ instance: T, toType type: T.Type) {
let id = ObjectIdentifier(type)
if let existingInstance = instances[id] {
fatalError("Cannot assign instance \(instance) to type \(type) because instance \(existingInstance) is already assigned")
}
instances[id] = instance
}
// Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to expect the returned instance to be a non-optional.
public func get<T>() -> T? {
return get(T.self)
}
public func get<T>(_ type: T.Type) -> T? {
let id = ObjectIdentifier(type)
return instances[id] as! T?
}
// Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to expect the returned instance to be a non-optional.
public func require<T>() -> T {
return require(T.self)
}
public func require<T>(_ type: T.Type) -> T {
guard let instance = get(type) else {
fatalError("No instance was assigned to type \(type).")
}
return instance
}
// Be very careful to not call this method with an Optional or an ImplicitlyUnwrappedOptional type. Use `as` in this case to convert the instance type to a non-optional first.
public mutating func unassign<T>(_ type: T.Type) -> T? {
let id = ObjectIdentifier(type)
return instances.removeValue(forKey: id) as! T?
}
}
prefix operator <?
prefix operator <!
public prefix func <? <T>(dictionary: TypeInstanceDictionary) -> T? {
return dictionary.get()
}
public prefix func <! <T>(dictionary: TypeInstanceDictionary) -> T {
return dictionary.require()
}
| mit | d97b527c2422ef343a9f6518712671d1 | 28.246377 | 176 | 0.711596 | 3.74397 | false | false | false | false |
incetro/NIO | Example/NioExample-iOS/Models/Plain/PositionPlainObject.swift | 1 | 950 | //
// PositionPlainObject.swift
// Nio
//
// Created by incetro on 15/07/2017.
//
//
import NIO
import Transformer
// MARK: - PositionPlainObject
class PositionPlainObject: TransformablePlain {
var nioID: NioID {
return NioID(value: id)
}
let id: Int64
let name: String
let price: Double
init(with name: String, price: Double, id: Int64) {
self.name = name
self.id = id
self.price = price
}
var category: CategoryPlainObject? = nil
var additives: [AdditivePlainObject] = []
required init(with resolver: Resolver) throws {
self.id = try resolver.value("id")
self.name = try resolver.value("name")
self.price = try resolver.value("price")
self.category = try? resolver.value("category")
self.additives = (try? resolver.value("additives")) ?? []
}
}
| mit | 1c053f49254078abd926320ed33d1b67 | 20.590909 | 65 | 0.568421 | 3.815261 | false | false | false | false |
codefellows/sea-b19-ios | Projects/CoreDataMusic/CoreDataMusic/ViewController.swift | 1 | 5970 | //
// ViewController.swift
// CoreDataMusic
//
// Created by Bradley Johnson on 8/19/14.
// Copyright (c) 2014 learnswift. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate, NSFetchedResultsControllerDelegate {
var myContext : NSManagedObjectContext!
var labels = [Label]()
@IBOutlet weak var tableView: UITableView!
var fetchedResultsController : NSFetchedResultsController!
override func viewDidLoad() {
super.viewDidLoad()
var appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
self.myContext = appDelegate.managedObjectContext
self.setupFetchedResultsController()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var error : NSError?
fetchedResultsController?.performFetch(&error)
if error != nil {
println(error?.localizedDescription)
}
}
func setupFetchedResultsController() {
let fetchRequest = NSFetchRequest(entityName: "Label")
let sort = NSSortDescriptor(key: "name", ascending: false)
fetchRequest.sortDescriptors = [sort]
fetchRequest.fetchBatchSize = 25
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.myContext, sectionNameKeyPath: nil, cacheName: nil)
self.fetchedResultsController.delegate = self
}
@IBAction func addLabelPressed(sender: AnyObject) {
self.performSegueWithIdentifier("addLabel", sender: self)
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.fetchedResultsController!.sections[section].numberOfObjects
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("LabelCell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, forIndexPath: indexPath)
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "addLabel" {
let addLabelVC = segue.destinationViewController as AddLabelViewController
} else if segue.identifier == "ShowArtists" {
let artistsVC = segue.destinationViewController as ArtistsViewController
var labelForRow = self.fetchedResultsController.fetchedObjects[self.tableView.indexPathForSelectedRow().row] as Label
artistsVC.selectedLabel = labelForRow
}
}
//MARK: NSFetchedResultsControllerDelegate Methods
func controllerWillChangeContent(controller: NSFetchedResultsController!) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController!, didChangeSection sectionInfo: NSFetchedResultsSectionInfo!, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
self.tableView.reloadSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
}
}
func configureCell(cell: UITableViewCell, forIndexPath indexPath: NSIndexPath) {
var labelForRow = self.fetchedResultsController.fetchedObjects[indexPath.row] as Label
cell.textLabel.text = labelForRow.name
}
func controller(controller: NSFetchedResultsController!, didChangeObject anObject: AnyObject!, atIndexPath indexPath: NSIndexPath!, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath!) {
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
self.configureCell(self.tableView.cellForRowAtIndexPath(indexPath), forIndexPath: indexPath)
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
self.tableView.endUpdates()
}
//MARK: Table View Re-Ordering
func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
// don't need anything here, just have to implement it for the respondsToSelector test
}
func tableView(tableView: UITableView!, editActionsForRowAtIndexPath indexPath: NSIndexPath!) -> [AnyObject]! {
let deleteAction = UITableViewRowAction(style: .Default, title: "Delete") { (action, indexPath) -> Void in
println("Delete Action")
if let labelForRow = self.fetchedResultsController.fetchedObjects[indexPath.row] as? Label {
self.myContext.deleteObject(labelForRow)
}
}
deleteAction.backgroundColor = UIColor.redColor()
let editAction = UITableViewRowAction(style: .Default, title: "Edit") { (action, indexPath) -> Void in
println("Edit Action")
let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
}
editAction.backgroundColor = UIColor.lightGrayColor()
return [deleteAction, editAction]
}
}
| gpl-2.0 | fdb427ae69ef8db2927428e31195da32 | 41.042254 | 213 | 0.689615 | 6.129363 | false | false | false | false |
worchyld/EYPlayground | Factories.swift | 1 | 3425 | //
// Factories.swift
// EYGens
//
// Created by Amarjit on 15/12/2016.
// Copyright © 2016 Amarjit. All rights reserved.
//
import Foundation
class Factory : NSObject {
var generation : Generation
var suitColor: SuitColor
var active : Bool = false
var willObselete : Bool = false
var shouldObselete : Bool = false
override var description: String {
return ( "\(suitColor) \(generation.rawValue)" )
}
init(suitColor:SuitColor, gen:Generation, active:Bool? = false) {
self.generation = gen
self.suitColor = suitColor
self.active = active!
}
}
var allFactories = [
Factory.init(suitColor: .Green, gen: .First, active: true),
Factory.init(suitColor: .Red, gen: .First),
Factory.init(suitColor: .Yellow, gen: .First),
Factory.init(suitColor: .Blue, gen: .First),
Factory.init(suitColor: .Green, gen: .Second, active: true),
Factory.init(suitColor: .Red, gen: .Second),
Factory.init(suitColor: .Yellow, gen: .Second),
Factory.init(suitColor: .Green, gen: .Third),
Factory.init(suitColor: .Blue, gen: .Second),
Factory.init(suitColor: .Red, gen: .Second),
Factory.init(suitColor: .Green, gen: .Fourth),
Factory.init(suitColor: .Yellow, gen: .Third),
Factory.init(suitColor: .Red, gen: .Third),
Factory.init(suitColor: .Green, gen: .Fifth)
]
func printAllFactories() {
for (index, train) in allFactories.enumerated() {
print (index, train.description)
}
}
class Maker {
let greenReport = Reporting().activeGreen
let redReport = Reporting().activeRed
let blueReport = Reporting().activeBlue
let yellowReport = Reporting().activeYellow
func runner() {
print ("Assume 5 player game")
print ("REPORT")
print ("Greens = \(greenReport)")
print ("Red = \(redReport)")
print ("Blue = \(blueReport)")
print ("Yellow = \(yellowReport)")
print ("----")
// Generations check
print ("Generations check for green")
if (greenReport == 0)
{
print ("No generation exists, nothing is done for this type")
}
else if (greenReport == 1) {
print ("1 generation exists, check max dice")
var _ = allFactories.filter{
(f : Factory) -> Bool in
return (f.suitColor == .Green && f.active && f.generation == .First )}.first
// // Max dice check
// if (firstTrain!.salesDicePool.count < firstTrain!.dicePoolCapacity) {
// print ("This train has not reached capacity \(firstTrain!.salesDicePool.count) vs \(firstTrain!.dicePoolCapacity)")
//
// firstTrain!.addOrder(toPool: .Sales)
// }
// else {
// print ("This train has reached capacity")
// }
//
// // Re-roll all sales dice and transfer all dice back to orders
// firstTrain!.transferAllDiceBackToOrders()
}
else if (greenReport == 2) {
print ("2 generations exist, go to older lower gen and start transfers. Check newer gen for max dice")
}
else if (greenReport == 3) {
print ("3 generations exist, obselete the very oldest gen. Go up the chain and check for max dice")
}
else {
print ("Nothing happens")
}
}
}
| gpl-3.0 | 4d22b49c5efa351824a169d4525182a8 | 26.612903 | 133 | 0.587909 | 3.91762 | false | false | false | false |
siuying/SwiftyDispatch | Classes/Queue.swift | 1 | 4661 | //
// Dispatch.swift
// BlueWhale2
//
// Created by Chan Fai Chong on 14/8/15.
// Copyright © 2015 Ignition Soft. All rights reserved.
//
import Foundation
public struct Queue {
public let queue : dispatch_queue_t
public enum QueueType {
case Serial
case Concurrent
var value : dispatch_queue_attr_t? {
get {
switch self {
case .Serial:
return DISPATCH_QUEUE_SERIAL
case .Concurrent:
return DISPATCH_QUEUE_CONCURRENT
}
}
}
}
public enum Priority : Int {
case Background
case Default
case High
case Low
var value : Int {
get {
switch self {
case .Background:
return DISPATCH_QUEUE_PRIORITY_BACKGROUND
case .Default:
return DISPATCH_QUEUE_PRIORITY_DEFAULT
case .High:
return DISPATCH_QUEUE_PRIORITY_HIGH
case .Low:
return DISPATCH_QUEUE_PRIORITY_LOW
}
}
}
}
public enum QOS : UInt {
case UserInteractive
case UserInitiated
case Default
case Utility
case Background
var value : qos_class_t {
get {
switch self {
case .UserInteractive:
return QOS_CLASS_USER_INTERACTIVE
case .UserInitiated:
return QOS_CLASS_USER_INITIATED
case .Default:
return QOS_CLASS_DEFAULT
case .Utility:
return QOS_CLASS_UTILITY
case .Background:
return QOS_CLASS_BACKGROUND
}
}
}
}
public var label : String {
get {
return String.fromCString(dispatch_queue_get_label(queue))!
}
}
/// Create a Queue object with a dispatch_queue_t
///
/// - Parameter queue: underlying dispatch_queue_t object
public init(queue: dispatch_queue_t) {
self.queue = queue
}
/// Create a Queue with label and type
///
/// - Parameter label: label of the queue
/// - Parameter type: Type of the queue (QueueType)
public init(_ label: String, _ type: QueueType = .Serial) {
self.queue = dispatch_queue_create(label, type.value)
}
/// Run a block asynchronously
///
/// - Parameter block: The block to run
public func async(block: dispatch_block_t) {
dispatch_async(self.queue, block)
}
/// Set Target Queue of current queue, using QoS
public func setTargetQoS(qos: Queue.QOS) {
dispatch_set_target_queue(self.queue, dispatch_get_global_queue(qos.value, 0))
}
/// Set Target Queue of current queue, using priority
public func setTargetPriority(priority: Queue.Priority) {
dispatch_set_target_queue(self.queue, dispatch_get_global_queue(priority.value, 0))
}
/// Run a block synchronously
///
/// - Parameter block: The block to run
public func sync(block: dispatch_block_t) {
dispatch_sync(self.queue, block)
}
/// Submits a block to run for multiple times.
///
/// - Parameter iterations: Number of iterations
/// - Parameter block: The block to run
public func apply(iterations: Int, block: (Int) -> Void) {
dispatch_apply(iterations, queue, block)
}
/// Schedule a block at a specified time.
///
/// - Parameter delayInSeconds: Delay in number of seconds
/// - Parameter block: The block to run
public func after(delayInSeconds: Double, block: dispatch_block_t) {
let nanoSeconds = Int64(Double(NSEC_PER_SEC) * delayInSeconds)
let delayTime = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds)
dispatch_after(delayTime, queue, block)
}
/// Returns the default queue that is bound to the main thread.
public static func main() -> Queue {
return Queue(queue: dispatch_get_main_queue())
}
/// Returns a global queue by QOS
/// - Parameter qos: the QOS of the queue
public static func concurrent(qos: Queue.QOS) -> Queue {
return Queue(queue: dispatch_get_global_queue(qos.value, 0))
}
/// Returns a global queue by Priotity
/// - Parameter priority: the priority of the queue
public static func concurrent(priority priority: Queue.Priority) -> Queue {
return Queue(queue: dispatch_get_global_queue(priority.value, 0))
}
} | mit | 002114772408a51a5f621a1dae2fb45d | 29.070968 | 91 | 0.56824 | 4.646062 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/DiscussionHelper.swift | 1 | 5090 | //
// DiscussionHelper.swift
// edX
//
// Created by Saeed Bashir on 2/18/16.
// Copyright © 2016 edX. All rights reserved.
//
import Foundation
class DiscussionHelper: NSObject {
class func updateEndorsedTitle(thread: DiscussionThread, label: UILabel, textStyle: OEXTextStyle) {
let endorsedIcon = Icon.Answered.attributedTextWithStyle(textStyle, inline : true)
switch thread.type {
case .Question:
let endorsedText = textStyle.attributedStringWithText(Strings.answer)
label.attributedText = NSAttributedString.joinInNaturalLayout([endorsedIcon,endorsedText])
case .Discussion:
let endorsedText = textStyle.attributedStringWithText(Strings.endorsed)
label.attributedText = NSAttributedString.joinInNaturalLayout([endorsedIcon,endorsedText])
}
}
class func messageForError(error: NSError?) -> String {
if let error = error where error.oex_isNoInternetConnectionError {
return Strings.networkNotAvailableMessageTrouble
}
else {
return Strings.unknownError
}
}
class func showErrorMessage(controller: UIViewController?, error: NSError?) {
let controller = controller ?? UIApplication.sharedApplication().keyWindow?.rootViewController
if let error = error where error.oex_isNoInternetConnectionError {
UIAlertController().showAlertWithTitle(Strings.networkNotAvailableTitle, message: Strings.networkNotAvailableMessageTrouble, onViewController: controller ?? UIViewController())
}
else {
controller?.showOverlayMessage(Strings.unknownError)
}
}
class func styleAuthorProfileImageView(imageView: UIImageView) {
dispatch_async(dispatch_get_main_queue(),{
imageView.layer.cornerRadius = imageView.bounds.size.width / 2
imageView.layer.borderWidth = 1
imageView.layer.borderColor = OEXStyles.sharedStyles().primaryBaseColor().CGColor
imageView.clipsToBounds = true
imageView.layer.masksToBounds = true
})
}
class func profileImage(hasProfileImage: Bool, imageURL: String?) ->RemoteImage {
let placeholder = UIImage(named: "profilePhotoPlaceholder")
if let URL = imageURL where hasProfileImage {
return RemoteImageImpl(url: URL, networkManager: OEXRouter.sharedRouter().environment.networkManager, placeholder: placeholder, persist: true)
}
else {
return RemoteImageJustImage(image: placeholder)
}
}
class func styleAuthorDetails(author: String?, authorLabel: String?, createdAt: NSDate?, hasProfileImage: Bool, imageURL: String?, authoNameLabel: UILabel, dateLabel: UILabel, authorButton: UIButton, imageView: UIImageView, viewController: UIViewController, router: OEXRouter?) {
let textStyle = OEXTextStyle(weight:.Normal, size:.Base, color: OEXStyles.sharedStyles().neutralXDark())
// formate author name
let highlightStyle = OEXMutableTextStyle(textStyle: textStyle)
if let _ = author where OEXConfig.sharedConfig().profilesEnabled {
highlightStyle.color = OEXStyles.sharedStyles().primaryBaseColor()
highlightStyle.weight = .Bold
}
else {
highlightStyle.color = OEXStyles.sharedStyles().neutralXDark()
highlightStyle.weight = textStyle.weight
}
let authorName = highlightStyle.attributedStringWithText(author ?? Strings.anonymous.oex_lowercaseStringInCurrentLocale())
var attributedStrings = [NSAttributedString]()
attributedStrings.append(authorName)
if let authorLabel = authorLabel {
attributedStrings.append(textStyle.attributedStringWithText(Strings.parenthesis(text: authorLabel)))
}
let formattedAuthorName = NSAttributedString.joinInNaturalLayout(attributedStrings)
authoNameLabel.attributedText = formattedAuthorName
if let createdAt = createdAt {
dateLabel.attributedText = textStyle.attributedStringWithText(createdAt.displayDate)
}
let profilesEnabled = OEXConfig.sharedConfig().profilesEnabled
authorButton.enabled = profilesEnabled
if let author = author where profilesEnabled {
authorButton.oex_removeAllActions()
authorButton.oex_addAction({ [weak viewController] _ in
router?.showProfileForUsername(viewController, username: author ?? Strings.anonymous, editable: false)
}, forEvents: .TouchUpInside)
}
else {
// if post is by anonymous user then disable author button (navigating to user profile)
authorButton.enabled = false
}
authorButton.isAccessibilityElement = authorButton.enabled
imageView.remoteImage = profileImage(hasProfileImage, imageURL: imageURL)
}
}
| apache-2.0 | b13d69f57d727ef4cb36336b16c50ba4 | 43.252174 | 283 | 0.67361 | 5.869666 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Me/MyThreads/MyThreadsBaseTableViewModel.swift | 1 | 2930 | //
// MyThreadsBaseTableViewModel.swift
// HiPDA
//
// Created by leizh007 on 2017/7/9.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import RxSwift
class MyThreadsBaseTableViewModel {
var disposeBag = DisposeBag()
var models = [MyThreadsBaseModel]()
var page = 1
var maxPage = 1
var hasData: Bool {
return models.count > 0
}
var hasMoreData: Bool {
return page < maxPage
}
func numberOfItems() -> Int {
return models.count
}
func loadFirstPage(completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
self.page = 1
let page = 1
load(page: page) { [weak self] result in
guard let `self` = self, page == `self`.page else { return }
switch result {
case let .success((models: models, maxPage: maxPage)):
self.models = models
self.maxPage = maxPage
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
func loadNextPage(completion: @escaping (HiPDA.Result<Void, NSError>) -> Void) {
self.page += 1
let page = self.page
load(page: page) { [weak self] result in
guard let `self` = self, page == `self`.page else { return }
switch result {
case let .success((models: models, maxPage: maxPage)):
self.models.append(contentsOf: models)
self.maxPage = maxPage
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
func transform(html: String) throws -> [MyThreadsBaseModel] {
fatalError("Must be overrided!")
}
func api(at page: Int) -> HiPDA.API {
fatalError("Must be overrided!")
}
fileprivate func load(page: Int, completion: @escaping (HiPDA.Result<(models: [MyThreadsBaseModel], maxPage: Int), NSError>) -> Void) {
disposeBag = DisposeBag()
let transform = self.transform
HiPDAProvider.request(self.api(at: page))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInteractive))
.mapGBKString()
.map { (try transform($0), try HtmlParser.totalPage(from: $0)) }
.observeOn(MainScheduler.instance)
.subscribe { event in
switch event {
case .next(let (models, maxPage)):
completion(.success((models: models, maxPage: maxPage)))
case .error(let error):
completion(.failure(error as NSError))
default:
break
}
}.disposed(by: disposeBag)
}
func jumpURL(at index: Int) -> String {
fatalError("Must be overrided!")
}
}
| mit | 7898f6ce70a9de60dda974c761c2014d | 31.164835 | 139 | 0.546293 | 4.53096 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Preferences Window Views/PreferencesViewElements.swift | 1 | 80329 | //
// PreferencesViewElements.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
public func addSeparator(toView: NSView,
lastSubview: NSView?,
height: inout CGFloat,
topIndent: CGFloat?,
constraints: inout [NSLayoutConstraint],
sender: Any? = nil) -> NSView? {
// ---------------------------------------------------------------------
// Create and add vertical separator
// ---------------------------------------------------------------------
let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 * 2), height: 250.0))
separator.translatesAutoresizingMaskIntoConstraints = false
separator.boxType = .separator
toView.addSubview(separator)
// ---------------------------------------------------------------------
// Add Constraints
// ---------------------------------------------------------------------
// Top
var constantTop: CGFloat
if let topIndentValue = topIndent {
constantTop = topIndentValue
} else if sender is ProfileExportAccessoryView {
constantTop = 6.0
} else {
constantTop = 8.0
}
constraints.append(NSLayoutConstraint(item: separator,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Leading
constraints.append(NSLayoutConstraint(item: separator,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: 20.0))
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: separator,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// ---------------------------------------------------------------------
// Update height value
// ---------------------------------------------------------------------
height += constantTop + separator.intrinsicContentSize.height
return separator
}
public func addHeader(title: String,
controlSize: NSControl.ControlSize = .regular,
withSeparator: Bool,
textFieldTitle: NSTextField = NSTextField(),
toView: NSView,
lastSubview: NSView?,
height: inout CGFloat,
constraints: inout [NSLayoutConstraint],
sender: Any? = nil) -> NSView? {
// -------------------------------------------------------------------------
// Create and add TextField title
// -------------------------------------------------------------------------
textFieldTitle.translatesAutoresizingMaskIntoConstraints = false
textFieldTitle.lineBreakMode = .byTruncatingTail
textFieldTitle.isBordered = false
textFieldTitle.isBezeled = false
textFieldTitle.drawsBackground = false
textFieldTitle.isEditable = false
textFieldTitle.isSelectable = false
textFieldTitle.textColor = .labelColor
if sender is ProfileExportAccessoryView {
textFieldTitle.font = NSFont.systemFont(ofSize: NSFont.systemFontSize(for: controlSize), weight: .bold)
}
textFieldTitle.alignment = .left
textFieldTitle.stringValue = title
textFieldTitle.controlSize = controlSize
toView.addSubview(textFieldTitle)
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 20.0
if sender is ProfileExportAccessoryView {
constantTop = 10.0
}
constraints.append(NSLayoutConstraint(item: textFieldTitle,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Leading
// FIXME: Update functions to remove hardcoded class checks
// All of these hardcoded things is mostly to get things done faster, need to revisit to actually check all the custom needs and update the functions accordingly
if !(sender is ProfileExportAccessoryView) {
constraints.append(NSLayoutConstraint(item: textFieldTitle,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: 20.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: textFieldTitle,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textFieldTitle.intrinsicContentSize.height
if withSeparator {
// ---------------------------------------------------------------------
// Create and add vertical separator
// ---------------------------------------------------------------------
let separator = NSBox(frame: NSRect(x: 250.0, y: 15.0, width: kPreferencesWindowWidth - (20.0 * 2), height: 250.0))
separator.translatesAutoresizingMaskIntoConstraints = false
separator.boxType = .separator
toView.addSubview(separator)
// ---------------------------------------------------------------------
// Add Constraints
// ---------------------------------------------------------------------
// Top
constantTop = 8.0
if sender is ProfileExportAccessoryView {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: separator,
attribute: .top,
relatedBy: .equal,
toItem: textFieldTitle,
attribute: .bottom,
multiplier: 1,
constant: constantTop))
// Leading
if sender is ProfileExportAccessoryView {
constraints.append(NSLayoutConstraint(item: textFieldTitle,
attribute: .leading,
relatedBy: .equal,
toItem: separator,
attribute: .leading,
multiplier: 1,
constant: 0.0))
} else {
constraints.append(NSLayoutConstraint(item: separator,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: 20.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: separator,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// ---------------------------------------------------------------------
// Update height value
// ---------------------------------------------------------------------
height += 8.0 + separator.intrinsicContentSize.height
return separator
} else {
return textFieldTitle
}
}
func setupLabel(string: String?, controlSize: NSControl.ControlSize = .regular, toView: NSView, indent: CGFloat, constraints: inout [NSLayoutConstraint]) -> NSTextField? {
guard var labelString = string else { return nil }
if !labelString.hasSuffix(":") {
labelString.append(":")
}
// -------------------------------------------------------------------------
// Create and add TextField Label
// -------------------------------------------------------------------------
let textFieldLabel = NSTextField()
textFieldLabel.translatesAutoresizingMaskIntoConstraints = false
textFieldLabel.lineBreakMode = .byTruncatingTail
textFieldLabel.isBordered = false
textFieldLabel.isBezeled = false
textFieldLabel.drawsBackground = false
textFieldLabel.isEditable = false
textFieldLabel.isSelectable = true
textFieldLabel.textColor = .labelColor
textFieldLabel.alignment = .right
textFieldLabel.stringValue = labelString
textFieldLabel.controlSize = controlSize
textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(textFieldLabel)
// Leading
constraints.append(NSLayoutConstraint(item: textFieldLabel,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
return textFieldLabel
}
public func addColorWell(label: String?,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
bindKeyPath: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSColorWell? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints)
let colorWell = NSColorWell()
colorWell.translatesAutoresizingMaskIntoConstraints = false
colorWell.isBordered = true
toView.addSubview(colorWell)
// ---------------------------------------------------------------------
// Bind color well to keyPath
// ---------------------------------------------------------------------
colorWell.bind(NSBindingName.value,
to: bindTo ?? UserDefaults.standard,
withKeyPath: bindKeyPath,
options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.valueTransformerName: HexColorTransformer.name])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Width
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 44.0))
// True
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 23.0))
if let label = textFieldLabel {
// Top
var constantTop: CGFloat = 16.0
if controlSize == .small {
constantTop = 7.0
}
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Leading
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .leading,
relatedBy: .equal,
toItem: label,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .centerY,
relatedBy: .equal,
toItem: label,
attribute: .centerY,
multiplier: 1,
constant: 0.0))
} else {
// Top
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: 6.0))
}
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
} else if textFieldLabel == nil {
// Leading
constraints.append(NSLayoutConstraint(item: colorWell,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: colorWell,
attribute: .trailing,
multiplier: 1,
constant: 20))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 8.0 + colorWell.intrinsicContentSize.height
return colorWell
}
public func addDirectoryPathSelection(label: String?,
placeholderValue: String,
buttonTitle: String?,
buttonTarget: Any?,
buttonAction: Selector,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
keyPath: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
let textFieldLabel = NSTextField()
if let labelString = label {
// -------------------------------------------------------------------------
// Create and add TextField Label
// -------------------------------------------------------------------------
textFieldLabel.translatesAutoresizingMaskIntoConstraints = false
textFieldLabel.lineBreakMode = .byTruncatingTail
textFieldLabel.isBordered = false
textFieldLabel.isBezeled = false
textFieldLabel.drawsBackground = false
textFieldLabel.isEditable = false
textFieldLabel.isSelectable = true
textFieldLabel.textColor = .labelColor
textFieldLabel.alignment = .right
textFieldLabel.stringValue = labelString
textFieldLabel.controlSize = controlSize
textFieldLabel.setContentHuggingPriority(.required, for: .horizontal)
textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(textFieldLabel)
// Leading
constraints.append(NSLayoutConstraint(item: textFieldLabel,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: kPreferencesIndent))
}
// -------------------------------------------------------------------------
// Create and add TextField
// -------------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingMiddle
textField.isBordered = false
textField.isBezeled = false
textField.bezelStyle = .squareBezel
textField.drawsBackground = false
textField.isEditable = false
textField.isSelectable = true
textField.textColor = .labelColor
textField.alignment = .left
textField.placeholderString = placeholderValue
textField.controlSize = controlSize
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
textField.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
textField.setContentHuggingPriority(.defaultLow, for: .horizontal)
textField.setContentHuggingPriority(.defaultLow, for: .vertical)
toView.addSubview(textField)
// ---------------------------------------------------------------------
// Bind TextField to keyPath
// ---------------------------------------------------------------------
textField.bind(NSBindingName.value,
to: bindTo ?? UserDefaults.standard,
withKeyPath: keyPath,
options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue])
// -------------------------------------------------------------------------
// Create and add button
// -------------------------------------------------------------------------
let button = NSButton(title: buttonTitle ?? NSLocalizedString("Choose…", comment: ""), target: buttonTarget, action: buttonAction)
button.translatesAutoresizingMaskIntoConstraints = false
button.controlSize = controlSize
button.setContentCompressionResistancePriority(.required, for: .horizontal)
button.setContentHuggingPriority(.required, for: .horizontal)
toView.addSubview(button)
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// TextField Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Checkbox Center Y
constraints.append(NSLayoutConstraint(item: textField,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
// Button Leading
constraints.append(NSLayoutConstraint(item: button,
attribute: .leading,
relatedBy: .equal,
toItem: textField,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Button Baseline
constraints.append(NSLayoutConstraint(item: button,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: button,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textField.intrinsicContentSize.height
return textField
}
public func addPopUpButtonCertificate(label: String?,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
bindKeyPathCheckbox: String,
bindKeyPathPopUpButton: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
guard let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) else { return nil }
var menu: NSMenu
var signingCertificatePersistantRef: Data?
if
let userDefaults = bindTo as? UserDefaults,
let persistantRef = userDefaults.data(forKey: bindKeyPathPopUpButton) {
signingCertificatePersistantRef = persistantRef
} else if
let bindObject = bindTo as? NSObject,
let persistantRef = bindObject.value(forKeyPath: bindKeyPathPopUpButton) as? Data {
signingCertificatePersistantRef = persistantRef
}
if let identityDict = Identities.codeSigningIdentityDict(persistentRef: signingCertificatePersistantRef) {
menu = Identities.popUpButtonMenu(forCodeSigningIdentityDicts: [identityDict])
} else {
menu = NSMenu()
menu.addItem(NSMenuItem(title: "None", action: nil, keyEquivalent: ""))
}
// -------------------------------------------------------------------------
// Create and add Checkbox
// -------------------------------------------------------------------------
let checkbox = NSButton()
checkbox.translatesAutoresizingMaskIntoConstraints = false
checkbox.setButtonType(.switch)
checkbox.title = ""
toView.addSubview(checkbox)
// ---------------------------------------------------------------------
// Bind checkbox to keyPath
// ---------------------------------------------------------------------
checkbox.bind(.value,
to: bindTo ?? UserDefaults.standard,
withKeyPath: bindKeyPathCheckbox,
options: [.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Create and add PopUpButton
// -------------------------------------------------------------------------
let popUpButton = SigningCertificatePopUpButton()
popUpButton.translatesAutoresizingMaskIntoConstraints = false
popUpButton.controlSize = controlSize
popUpButton.menu = menu
popUpButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
popUpButton.setContentHuggingPriority(.defaultLow, for: .horizontal)
toView.addSubview(popUpButton)
menu.delegate = popUpButton
// ---------------------------------------------------------------------
// Bind PopUpButton to keyPath
// ---------------------------------------------------------------------
popUpButton.bind(.selectedObject,
to: bindTo ?? UserDefaults.standard,
withKeyPath: bindKeyPathPopUpButton,
options: [.continuouslyUpdatesValue: true])
// ---------------------------------------------------------------------
// Bind PopUpButton to checkbox state
// ---------------------------------------------------------------------
popUpButton.bind(.enabled,
to: bindTo ?? UserDefaults.standard,
withKeyPath: bindKeyPathCheckbox,
options: [.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 8.0
if lastSubview is NSButton {
constantTop = 8.0
} else if controlSize == .small {
constantTop = 6.0
}
// Top
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Checkbox Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Checkbox Center Y
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
// PopUpButton Leading
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .leading,
relatedBy: .equal,
toItem: checkbox,
attribute: .trailing,
multiplier: 1,
constant: 1.0))
// PopUpButton Baseline
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: popUpButton,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 8.0 + popUpButton.intrinsicContentSize.height
return popUpButton
}
class SigningCertificatePopUpButton: NSPopUpButton, NSMenuDelegate {
func menuWillOpen(_ menu: NSMenu) {
let persistentRef = self.selectedItem?.representedObject as? Data
Identities.shared.updateCodeSigningIdentities()
menu.removeAllItems()
menu.addItem(NSMenuItem(title: "None", action: nil, keyEquivalent: ""))
for identity in Identities.shared.identities {
guard
let secIdentityObject = identity[kSecValueRef as String],
CFGetTypeID(secIdentityObject) == SecIdentityGetTypeID(),
let secPersistentRef = identity[kSecValuePersistentRef as String] as? Data else {
continue
}
// swiftlint:disable:next force_cast
let secIdentity = secIdentityObject as! SecIdentity
let menuItem = NSMenuItem()
menuItem.title = identity[kSecAttrLabel as String] as? String ?? "Unknown Certificate"
menuItem.representedObject = secPersistentRef
menuItem.image = secIdentity.certificateIconSmall
menu.addItem(menuItem)
}
self.selectItem(at: menu.indexOfItem(withRepresentedObject: persistentRef))
}
}
public func addButton(label: String?,
title: String?,
controlSize: NSControl.ControlSize = .regular,
bindToEnabled: Any?,
bindKeyPathEnabled: String?,
target: Any?,
selector: Selector,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints)
// -------------------------------------------------------------------------
// Create and add button
// -------------------------------------------------------------------------
let button = NSButton(title: title ?? NSLocalizedString("Choose…", comment: ""), target: target, action: selector)
button.translatesAutoresizingMaskIntoConstraints = false
button.controlSize = controlSize
button.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(button)
// ---------------------------------------------------------------------
// Bind Button enabled to checkbox state
// ---------------------------------------------------------------------
if let keyPath = bindKeyPathEnabled {
button.bind(NSBindingName.enabled, to: bindToEnabled ?? UserDefaults.standard, withKeyPath: keyPath, options: [.continuouslyUpdatesValue: true])
}
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
if let label = textFieldLabel {
// Leading
constraints.append(NSLayoutConstraint(item: button,
attribute: .leading,
relatedBy: .equal,
toItem: label,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: button,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: label,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
} else if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: button,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
} else {
// Leading
constraints.append(NSLayoutConstraint(item: button,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
}
// Top
constraints.append(NSLayoutConstraint(item: button,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: 8.0))
// Trailing
if lastTextField is NSButton, let lastButton = lastTextField {
constraints.append(NSLayoutConstraint(item: lastButton,
attribute: .trailing,
relatedBy: .equal,
toItem: button,
attribute: .trailing,
multiplier: 1,
constant: 0.0))
} else {
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: button,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
}
// Width
constraints.append(NSLayoutConstraint(item: button,
attribute: .width,
relatedBy: .greaterThanOrEqual,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: button.intrinsicContentSize.width))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 8.0 + button.intrinsicContentSize.height
return button
}
public func addPopUpButton(label: String?,
titles: [String],
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
bindKeyPath: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints)
// -------------------------------------------------------------------------
// Create and add PopUpButton
// -------------------------------------------------------------------------
let popUpButton = NSPopUpButton()
popUpButton.translatesAutoresizingMaskIntoConstraints = false
popUpButton.addItems(withTitles: titles)
popUpButton.controlSize = controlSize
popUpButton.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
toView.addSubview(popUpButton)
// ---------------------------------------------------------------------
// Bind PopUpButton to keyPath
// ---------------------------------------------------------------------
popUpButton.bind(NSBindingName.selectedValue, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [NSBindingOption.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 6.0
if controlSize == .small {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
if let label = textFieldLabel {
// Leading
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .leading,
relatedBy: .equal,
toItem: label,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: label,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
} else {
// Leading
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
}
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: popUpButton,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// Width
constraints.append(NSLayoutConstraint(item: popUpButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: popUpButton.intrinsicContentSize.width))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 8.0 + popUpButton.intrinsicContentSize.height
return popUpButton
}
public func addCheckbox(label: String?,
title: String,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
bindKeyPath: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints)
// -------------------------------------------------------------------------
// Create and add Checkbox
// -------------------------------------------------------------------------
let checkbox = NSButton()
checkbox.translatesAutoresizingMaskIntoConstraints = false
checkbox.setButtonType(.switch)
checkbox.title = title
checkbox.controlSize = controlSize
toView.addSubview(checkbox)
// ---------------------------------------------------------------------
// Bind checkbox to keyPath
// ---------------------------------------------------------------------
checkbox.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPath, options: [.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
if let label = textFieldLabel {
// Top
var constantTop: CGFloat = 16.0
if controlSize == .small {
constantTop = 7.0
}
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: label,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: label,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
} else {
var constantTop: CGFloat = 6.0
if bindTo is ProfileExportAccessoryView {
constantTop = 10.0
}
// Top
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
}
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
} else if textFieldLabel == nil {
// Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .greaterThanOrEqual,
toItem: checkbox,
attribute: .trailing,
multiplier: 1,
constant: 20))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 8.0 + checkbox.intrinsicContentSize.height
return checkbox
}
public func addTextFieldDescription(stringValue: String,
controlSize: NSControl.ControlSize = .regular,
font: NSFont? = nil,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
let textFieldDescription = NSTextField()
// -------------------------------------------------------------------------
// Create and add TextField Label
// -------------------------------------------------------------------------
textFieldDescription.translatesAutoresizingMaskIntoConstraints = false
textFieldDescription.lineBreakMode = .byWordWrapping
textFieldDescription.isBordered = false
textFieldDescription.isBezeled = false
textFieldDescription.drawsBackground = false
textFieldDescription.isEditable = false
textFieldDescription.isSelectable = true
textFieldDescription.textColor = .labelColor
textFieldDescription.alignment = .left
textFieldDescription.stringValue = stringValue
textFieldDescription.controlSize = controlSize
textFieldDescription.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(textFieldDescription)
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 8.0
if lastSubview == nil {
constantTop = 10.0
} else if controlSize == .small {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: textFieldDescription,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Leading
constraints.append(NSLayoutConstraint(item: textFieldDescription,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField ?? toView,
attribute: .leading,
multiplier: 1,
constant: (lastTextField != nil) ? 0.0 : kPreferencesIndent))
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: textFieldDescription,
attribute: .trailing,
multiplier: 1,
constant: 20))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textFieldDescription.intrinsicContentSize.height
return textFieldDescription
}
public func addTextFieldLabel(label: String?,
placeholderValue: String,
controlSize: NSControl.ControlSize = .regular,
font: NSFont? = nil,
bindTo: Any? = nil,
keyPath: String?,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
let textFieldLabel = NSTextField()
if let labelString = label {
// -------------------------------------------------------------------------
// Create and add TextField Label
// -------------------------------------------------------------------------
textFieldLabel.translatesAutoresizingMaskIntoConstraints = false
textFieldLabel.lineBreakMode = .byTruncatingTail
textFieldLabel.isBordered = false
textFieldLabel.isBezeled = false
textFieldLabel.drawsBackground = false
textFieldLabel.isEditable = false
textFieldLabel.isSelectable = true
textFieldLabel.textColor = .labelColor
textFieldLabel.alignment = .right
textFieldLabel.stringValue = labelString
textFieldLabel.controlSize = controlSize
textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(textFieldLabel)
// Leading
constraints.append(NSLayoutConstraint(item: textFieldLabel,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: kPreferencesIndent))
}
// -------------------------------------------------------------------------
// Create and add TextField
// -------------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingTail
textField.isBordered = false
textField.isBezeled = false
textField.drawsBackground = false
textField.isEditable = false
textField.isSelectable = true
textField.textColor = .labelColor
textField.alignment = .left
textField.placeholderString = placeholderValue
textField.controlSize = controlSize
if let textFieldFont = font {
textField.font = textFieldFont
}
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
toView.addSubview(textField)
// ---------------------------------------------------------------------
// Bind TextField to keyPath
// ---------------------------------------------------------------------
if let bindKeyPath = keyPath {
textField.bind(NSBindingName.value,
to: bindTo ?? UserDefaults.standard,
withKeyPath: bindKeyPath,
options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue])
}
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 8.0
if lastSubview == nil {
constantTop = 10.0
} else if controlSize == .small {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: textField,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
if label != nil {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: textField,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
} else {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: kPreferencesIndent))
}
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: textField,
attribute: .trailing,
multiplier: 1,
constant: 20))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textField.intrinsicContentSize.height
return textField
}
public func addTextField(label: String?,
placeholderValue: String,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any? = nil,
keyPath: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
let textFieldLabel = NSTextField()
if let labelString = label {
// -------------------------------------------------------------------------
// Create and add TextField Label
// -------------------------------------------------------------------------
textFieldLabel.translatesAutoresizingMaskIntoConstraints = false
textFieldLabel.lineBreakMode = .byTruncatingTail
textFieldLabel.isBordered = false
textFieldLabel.isBezeled = false
textFieldLabel.drawsBackground = false
textFieldLabel.isEditable = false
textFieldLabel.isSelectable = true
textFieldLabel.textColor = .labelColor
textFieldLabel.alignment = .right
textFieldLabel.stringValue = labelString
textFieldLabel.controlSize = controlSize
textFieldLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
toView.addSubview(textFieldLabel)
// Leading
constraints.append(NSLayoutConstraint(item: textFieldLabel,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: kPreferencesIndent))
}
// -------------------------------------------------------------------------
// Create and add TextField
// -------------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingTail
textField.isBordered = true
textField.isBezeled = true
textField.bezelStyle = .squareBezel
textField.drawsBackground = false
textField.isEditable = true
textField.isSelectable = true
textField.textColor = .labelColor
textField.alignment = .left
textField.placeholderString = placeholderValue
textField.controlSize = controlSize
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
toView.addSubview(textField)
// ---------------------------------------------------------------------
// Bind TextField to keyPath
// ---------------------------------------------------------------------
textField.bind(NSBindingName.value,
to: bindTo ?? UserDefaults.standard,
withKeyPath: keyPath,
options: [NSBindingOption.continuouslyUpdatesValue: true, NSBindingOption.nullPlaceholder: placeholderValue])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 8.0
if lastSubview == nil {
constantTop = 10.0
} else if controlSize == .small {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: textField,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
if label != nil {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Baseline
constraints.append(NSLayoutConstraint(item: textField,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
} else {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: kPreferencesIndent))
}
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: textField,
attribute: .trailing,
multiplier: 1,
constant: 20))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textField.intrinsicContentSize.height
return textField
}
public func addBox(title: String?,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSBox? {
let box = NSBox()
box.translatesAutoresizingMaskIntoConstraints = false
if let theTitle = title {
box.title = theTitle
box.titlePosition = .atTop
} else {
box.titlePosition = .noTitle
}
toView.addSubview(box)
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
let constantTop: CGFloat = -4.0
constraints.append(NSLayoutConstraint(item: box,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: box,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
} else {
// Leading
constraints.append(NSLayoutConstraint(item: box,
attribute: .leading,
relatedBy: .equal,
toItem: toView,
attribute: .leading,
multiplier: 1,
constant: indent))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: box,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
/*
// Height Test
constraints.append(NSLayoutConstraint(item: box,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 80.0))
*/
// ---------------------------------------------------------------------
// Update height value
// ---------------------------------------------------------------------
height += constantTop + box.intrinsicContentSize.height
return box
}
public func addTextField(label: String,
placeholderValue: String,
controlSize: NSControl.ControlSize = .regular,
bindTo: Any?,
bindKeyPathCheckbox: String,
bindKeyPathTextField: String,
toView: NSView,
lastSubview: NSView?,
lastTextField: NSView?,
height: inout CGFloat,
indent: CGFloat,
constraints: inout [NSLayoutConstraint]) -> NSView? {
// -------------------------------------------------------------------------
// Create and add Label if label string was passed
// -------------------------------------------------------------------------
guard let textFieldLabel = setupLabel(string: label, controlSize: controlSize, toView: toView, indent: indent, constraints: &constraints) else { return nil }
// -------------------------------------------------------------------------
// Create and add Checkbox
// -------------------------------------------------------------------------
let checkbox = NSButton()
checkbox.translatesAutoresizingMaskIntoConstraints = false
checkbox.setButtonType(.switch)
checkbox.title = ""
toView.addSubview(checkbox)
// ---------------------------------------------------------------------
// Bind checkbox to keyPath
// ---------------------------------------------------------------------
checkbox.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [NSBindingOption.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Create and add TextField
// -------------------------------------------------------------------------
let textField = NSTextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.lineBreakMode = .byTruncatingTail
textField.isBordered = true
textField.isBezeled = true
textField.bezelStyle = .squareBezel
textField.drawsBackground = false
textField.isEditable = true
textField.isSelectable = true
textField.textColor = .labelColor
textField.alignment = .left
textField.placeholderString = placeholderValue
textField.controlSize = controlSize
textField.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
toView.addSubview(textField)
// ---------------------------------------------------------------------
// Bind TextField to keyPath
// ---------------------------------------------------------------------
textField.bind(NSBindingName.value, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathTextField, options: [.continuouslyUpdatesValue: true, .nullPlaceholder: placeholderValue])
// ---------------------------------------------------------------------
// Bind PopUpButton to checkbox state
// ---------------------------------------------------------------------
textField.bind(NSBindingName.enabled, to: bindTo ?? UserDefaults.standard, withKeyPath: bindKeyPathCheckbox, options: [.continuouslyUpdatesValue: true])
// -------------------------------------------------------------------------
// Add Constraints
// -------------------------------------------------------------------------
// Top
var constantTop: CGFloat = 8.0
if lastSubview is NSButton {
constantTop = 8.0
} else if lastSubview is NSTextField {
constantTop = 5.0
} else if controlSize == .small {
constantTop = 6.0
}
constraints.append(NSLayoutConstraint(item: textField,
attribute: .top,
relatedBy: .equal,
toItem: lastSubview ?? toView,
attribute: (lastSubview != nil) ? .bottom : .top,
multiplier: 1,
constant: constantTop))
// Checkbox Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .trailing,
multiplier: 1,
constant: 6.0))
// Checkbox Center Y
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
// TextField Leading
constraints.append(NSLayoutConstraint(item: textField,
attribute: .leading,
relatedBy: .equal,
toItem: checkbox,
attribute: .trailing,
multiplier: 1,
constant: 0.0))
// TextField Baseline
constraints.append(NSLayoutConstraint(item: textField,
attribute: .firstBaseline,
relatedBy: .equal,
toItem: textFieldLabel,
attribute: .firstBaseline,
multiplier: 1,
constant: 0.0))
if lastTextField != nil {
// Leading
constraints.append(NSLayoutConstraint(item: checkbox,
attribute: .leading,
relatedBy: .equal,
toItem: lastTextField,
attribute: .leading,
multiplier: 1,
constant: 0.0))
}
// Trailing
constraints.append(NSLayoutConstraint(item: toView,
attribute: .trailing,
relatedBy: .equal,
toItem: textField,
attribute: .trailing,
multiplier: 1,
constant: 20.0))
// -------------------------------------------------------------------------
// Update height value
// -------------------------------------------------------------------------
height += 20.0 + textField.intrinsicContentSize.height
return checkbox
}
| mit | 8a09228cdd86b24ec6f1b3dc5138e2c1 | 46.388791 | 191 | 0.393021 | 7.919156 | false | false | false | false |
mokagio/GaugeKit | GaugeKit/CAShapeLayer+oval.swift | 2 | 4327 | //
// CAShapeLayer+oval.swift
// SWGauge
//
// Created by Petr Korolev on 03/06/15.
// Copyright (c) 2015 Petr Korolev. All rights reserved.
//
import Foundation
extension CAShapeLayer {
class func getLine(lineWidth: CGFloat,
strokeStart: CGFloat,
strokeEnd: CGFloat,
strokeColor: UIColor,
fillColor: UIColor,
shadowRadius: CGFloat,
shadowOpacity: Float,
shadowOffsset: CGSize,
bounds: CGRect,
rotateAngle: Double? = nil,
anchorPoint: CGPoint? = nil
) -> CAShapeLayer {
var arc = CAShapeLayer()
let rect = CGRectInset(bounds, CGFloat(lineWidth / 2.0), CGFloat(lineWidth / 2.0))
// let lineWidth: CGFloat = bounds.width - 2 * lineWidth
let path = CGPathCreateMutable()
let Y = CGRectGetMidY(bounds)
CGPathMoveToPoint(path, nil, lineWidth, Y)
CGPathAddLineToPoint(path, nil, bounds.width - lineWidth, Y)
arc.path = path
arc = setupArc(arc, lineWidth: lineWidth,
strokeStart: strokeStart,
strokeEnd: strokeEnd,
strokeColor: strokeColor,
fillColor: fillColor,
shadowRadius: shadowRadius,
shadowOpacity: shadowOpacity,
shadowOffsset: shadowOffsset,
rotateAngle: rotateAngle,
anchorPoint: anchorPoint)
return arc
}
class func getOval(lineWidth: CGFloat,
strokeStart: CGFloat,
strokeEnd: CGFloat,
strokeColor: UIColor,
fillColor: UIColor,
shadowRadius: CGFloat,
shadowOpacity: Float,
shadowOffsset: CGSize,
bounds: CGRect,
rotateAngle: Double? = nil,
anchorPoint: CGPoint? = nil,
isCircle: Bool = true
) -> CAShapeLayer {
var arc = CAShapeLayer()
let rect = CGRectInset(bounds, CGFloat(lineWidth / 2.0), CGFloat(lineWidth / 2.0))
if isCircle {
let arcDiameter: CGFloat = min(bounds.width, bounds.height) - 2 * lineWidth
let X = CGRectGetMidX(bounds)
let Y = CGRectGetMidY(bounds)
arc.path = UIBezierPath(ovalInRect: CGRectMake((X - (arcDiameter / 2)), (Y - (arcDiameter / 2)), arcDiameter, arcDiameter)).CGPath
} else {
arc.path = UIBezierPath(ovalInRect: rect).CGPath
}
arc = setupArc(arc, lineWidth: lineWidth,
strokeStart: strokeStart,
strokeEnd: strokeEnd,
strokeColor: strokeColor,
fillColor: fillColor,
shadowRadius: shadowRadius,
shadowOpacity: shadowOpacity,
shadowOffsset: shadowOffsset,
rotateAngle: rotateAngle,
anchorPoint: anchorPoint)
return arc
}
static func setupArc(arc: CAShapeLayer, lineWidth: CGFloat,
strokeStart: CGFloat,
strokeEnd: CGFloat,
strokeColor: UIColor,
fillColor: UIColor,
shadowRadius: CGFloat,
shadowOpacity: Float,
shadowOffsset: CGSize,
rotateAngle: Double? = nil,
anchorPoint: CGPoint? = nil) -> CAShapeLayer {
arc.lineWidth = lineWidth
arc.strokeStart = strokeStart
arc.strokeColor = strokeColor.CGColor
arc.fillColor = fillColor.CGColor
arc.shadowColor = UIColor.blackColor().CGColor
arc.shadowRadius = shadowRadius
arc.shadowOpacity = shadowOpacity
arc.shadowOffset = shadowOffsset
if let anchorPoint = anchorPoint {
arc.anchorPoint = anchorPoint
}
if let rotateAngle = rotateAngle {
arc.transform = CATransform3DRotate(arc.transform, CGFloat(rotateAngle), 0, 0, 1)
}
arc.strokeEnd = strokeEnd
return arc
}
}
| mit | 44e1640edaf634832eecb4432d779817 | 34.760331 | 142 | 0.529004 | 5.863144 | false | false | false | false |
salesforce-ux/design-system-ios | Demo-Swift/slds-sample-app/library/controls/ItemBar.swift | 1 | 4612 | // Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
import UIKit
protocol ItemBarDelegate {
func itemBar(_ itemBar: ItemBar, didSelectItemAt index: NSInteger)
}
class ItemBar: UIControl {
var items = Array<UIControl>()
var delegate : ItemBarDelegate?
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
var selectedIndex : Int = 0 {
didSet {
if let d = self.delegate {
d.itemBar(self, didSelectItemAt: selectedIndex)
}
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
var itemWidth : CGFloat {
return self.frame.width / CGFloat(self.items.count)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override init (frame : CGRect) {
super.init(frame : frame)
self.loadView()
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
convenience init () {
self.init(frame:CGRect.zero)
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func loadView() {
self.backgroundColor = UIColor.white
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
override func layoutSubviews() {
super.layoutSubviews()
for item in self.items {
item.heightConstraint.constant = self.frame.height
item.widthConstraint.constant = self.itemWidth
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func didSelectItemAt(sender: UIControl) {
if let index = items.index(of: sender) {
self.selectedIndex = index
}
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func removeItems() {
for item in self.items {
item.removeFromSuperview()
}
self.items.removeAll()
}
//––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
func addItem(item : UIControl) {
self.addSubview(item)
if items.count > 0 {
item.constrainRightOf(items.last!,
yAlignment: .bottom)
} else {
self.constrainChild(item,
xAlignment: .left,
yAlignment: .bottom)
}
self.items.append(item)
item.addTarget(self, action: #selector(ItemBar.didSelectItemAt(sender:)), for: .touchUpInside)
self.layoutIfNeeded()
}
}
| bsd-3-clause | 08d3376b8bb7796102659f59072c1d70 | 28.346154 | 102 | 0.389581 | 6.452431 | false | false | false | false |
fernandomarins/food-drivr-pt | hackathon-for-hunger/Modules/Driver/SignUp/Views/DriverSignupViewController.swift | 1 | 4995 | //
// VSUserInfoViewController.swift
// hackathon-for-hunger
//
// Created by ivan lares on 4/4/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import UIKit
enum State {
case IncompleteField
case NotEmail
case Custom(String, String)
case None
}
class DriverSignupViewController: UIViewController {
// Mark: Propety
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// Mark: Regular expression for email
private let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
private var user = UserRegistration()
private let signupPresenter = DriverSignupPresenter(userService: UserService())
var activityIndicator: ActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Registering")
signupPresenter.attachView(self)
}
// MARK: Actions
@IBAction func didPressSignUp(sender: AnyObject) {
let donorIsApproved = false
if donorIsApproved{
} else {
signUp()
}
}
// MARK: Navigation
func showAwaitingApprovalView(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let awaitingApprovalViewController = storyboard.instantiateViewControllerWithIdentifier("AwaitingApprovalDriverView") as! AwaitingApprovalDriverViewController
navigationController?.pushViewController(awaitingApprovalViewController, animated: true)
}
}
extension DriverSignupViewController {
func signUp() {
let validationState = isValid()
switch(validationState) {
case .None:
createUser()
sendToServer()
case .IncompleteField:
showAlert(validationState)
case .NotEmail:
showAlert(validationState)
default:
return
}
}
private func sendToServer() {
self.startLoading()
signupPresenter.register(self.user)
}
private func createUser() {
self.user.email = emailTextField.text
self.user.phone = phoneTextField.text
self.user.name = nameTextField.text
self.user.password = passwordTextField.text
self.user.role = .Donor
}
private func isValid() -> State {
if nameTextField.text == "" && phoneTextField.text == ""
&& emailTextField.text == "" && passwordTextField.text == "" {
return .IncompleteField
}else if !isValidEmail(emailTextField.text!) {
return .NotEmail
}
return .None
}
// check if the email is valid
private func isValidEmail(email: String) -> Bool {
let emailTest = NSPredicate(format:"SELF MATCHES %@", self.emailRegEx)
return emailTest.evaluateWithObject(email)
}
private func showAlert(state: State) {
var title = ""
var message = ""
let buttonTitle = "try"
switch state {
case .IncompleteField:
title = "Incomplete Field"
message = "Please ensure you complete all fields"
case .NotEmail:
title = "Incorrect email"
message = "Please ensure you enter a valid email"
case .Custom(let titleAlert, let messageAlert):
title = titleAlert
message = messageAlert
case .None:
return
}
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let alertAction = UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: nil )
alert.addAction(alertAction)
presentViewController(alert, animated: true, completion: nil)
}
}
extension DriverSignupViewController: SignupView {
func startLoading() {
self.activityIndicator.startAnimating()
}
func finishLoading() {
self.activityIndicator.stopAnimating()
}
func registration(sender: DriverSignupPresenter, didSucceed success: [String: AnyObject]) {
self.activityIndicator.stopAnimating()
self.showAwaitingApprovalView()
}
func registration(sender: DriverSignupPresenter, didFail error: NSError) {
self.activityIndicator.stopAnimating()
let alert = UIAlertController(title: "There was a problem", message: "Unable to register you at this time", preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil )
alert.addAction(alertAction)
presentViewController(alert, animated: true, completion: nil)
}
} | mit | 3e02c9247b3357dc2cb6c0bcd2f41418 | 28.732143 | 166 | 0.623949 | 5.229319 | false | false | false | false |
edx/edx-app-ios | Source/RatingViewController.swift | 1 | 7363 | //
// RatingViewController.swift
// edX
//
// Created by Danial Zahid on 1/23/17.
// Copyright © 2017 edX. All rights reserved.
//
import UIKit
import MessageUI
protocol RatingViewControllerDelegate {
func didDismissRatingViewController()
}
class RatingViewController: UIViewController, RatingContainerDelegate {
typealias Environment = DataManagerProvider & OEXInterfaceProvider & OEXStylesProvider & OEXConfigProvider & OEXAnalyticsProvider
var delegate : RatingViewControllerDelegate?
static let minimumPositiveRating : Int = 4
static let minimumVersionDifferenceForNegativeRating = 2
let environment : Environment
let ratingContainerView : RatingContainerView
var alertController : UIAlertController?
private var selectedRating : Int?
static func canShowAppReview(environment: Environment) -> Bool {
guard let _ = environment.config.appReviewURI, environment.interface?.reachable ?? false && environment.config.isAppReviewsEnabled else { return false }
if let appRating = environment.interface?.getSavedAppRating(), let lastVersionForAppReview = environment.interface?.getSavedAppVersionWhenLastRated(){
let version = Version(version: (Bundle.main.oex_shortVersionString()))
let savedVersion = Version(version: lastVersionForAppReview)
let validVersionDiff = version.isNMinorVersionsDiff(otherVersion: savedVersion, minorVersionDiff: minimumVersionDifferenceForNegativeRating)
if appRating >= minimumPositiveRating || !validVersionDiff {
return false
}
}
return true
}
init(environment : Environment) {
self.environment = environment
ratingContainerView = RatingContainerView(environment: environment)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
view.addSubview(ratingContainerView)
ratingContainerView.delegate = self
setupConstraints()
view.accessibilityElements = [ratingContainerView.subviews]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
environment.analytics.trackAppReviewScreen()
}
private func setupConstraints() {
ratingContainerView.snp.remakeConstraints { make in
make.centerX.equalTo(view.snp.centerX)
make.centerY.equalTo(view.snp.centerY)
make.width.equalTo(275)
}
}
//MARK: - RatingContainerDelegate methods
func didSubmitRating(rating: Int) {
selectedRating = Int(rating)
ratingContainerView.removeFromSuperview()
environment.analytics.trackSubmitRating(rating: rating)
switch rating {
case 1...3:
negativeRatingReceived()
break
case 4...5:
positiveRatingReceived()
break
default:
break
}
}
func closeButtonPressed() {
saveAppRating()
environment.analytics.trackDismissRating()
dismissViewController()
}
//MARK: - Positive Rating methods
private func positiveRatingReceived() {
alertController = UIAlertController().showAlert(withTitle: Strings.AppReview.rateTheApp, message: Strings.AppReview.positiveReviewMessage,cancelButtonTitle: nil, onViewController: self)
alertController?.addButton(withTitle: Strings.AppReview.maybeLater) {[weak self] (action) in
self?.saveAppRating()
if let rating = self?.selectedRating {
self?.environment.analytics.trackMaybeLater(rating: rating)
}
self?.dismissViewController()
}
alertController?.addButton(withTitle: Strings.AppReview.rateTheApp) {[weak self] (action) in
self?.saveAppRating(rating: self?.selectedRating)
if let rating = self?.selectedRating {
self?.environment.analytics.trackRateTheApp(rating: rating)
}
self?.sendUserToAppStore()
self?.dismissViewController()
}
}
private func sendUserToAppStore() {
guard let url = URL(string: environment.config.appReviewURI ?? "") else { return }
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
//MARK: - Negative Rating methods
private func negativeRatingReceived() {
alertController = UIAlertController().showAlert(withTitle: Strings.AppReview.sendFeedbackTitle, message: Strings.AppReview.helpUsImprove,cancelButtonTitle: nil, onViewController: self)
alertController?.addButton(withTitle: Strings.AppReview.maybeLater) {[weak self] (action) in
self?.saveAppRating()
if let rating = self?.selectedRating {
self?.environment.analytics.trackMaybeLater(rating: rating)
}
self?.dismissViewController()
}
alertController?.addButton(withTitle: Strings.AppReview.sendFeedback) {[weak self] (action) in
self?.saveAppRating(rating: self?.selectedRating)
if let rating = self?.selectedRating {
self?.environment.analytics.trackSendFeedback(rating: rating)
}
self?.launchEmailComposer()
}
}
//MARK: - Persistence methods
func saveAppRating(rating: Int? = 0) {
environment.interface?.saveAppRating(rating: rating ?? 0)
environment.interface?.saveAppVersionWhenLastRated()
}
//MARK: - Expose for testcases
func setRating(rating: Int) {
ratingContainerView.setRating(rating: rating)
}
func dismissViewController() {
dismiss(animated: false) {[weak self] in
self?.delegate?.didDismissRatingViewController()
}
}
}
extension RatingViewController : MFMailComposeViewControllerDelegate {
func launchEmailComposer() {
if !MFMailComposeViewController.canSendMail() {
UIAlertController().showAlert(withTitle: Strings.emailAccountNotSetUpTitle, message: Strings.emailAccountNotSetUpMessage, onViewController: self)
dismissViewController()
} else {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.navigationBar.tintColor = OEXStyles.shared().navigationItemTintColor()
mail.setSubject(Strings.AppReview.messageSubject)
mail.setMessageBody(EmailTemplates.supportEmailMessageTemplate(), isHTML: false)
if let fbAddress = environment.config.feedbackEmailAddress() {
mail.setToRecipients([fbAddress])
}
present(mail, animated: true, completion: nil)
}
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
dismissViewController()
}
}
| apache-2.0 | a925cba51bcb85fdd1940c2c9ffd6135 | 37.145078 | 193 | 0.659739 | 5.32321 | false | false | false | false |
Yalantis/PixPic | PixPic/Classes/DTO/Complaint.swift | 1 | 1556 | //
// Complaint.swift
// PixPic
//
// Created by Illya on 3/1/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
class Complaint: PFObject {
@NSManaged var complainer: User
@NSManaged var complaintReason: String
@NSManaged var suspectedUser: User
@NSManaged var suspectedPost: Post?
private static var onceToken: dispatch_once_t = 0
override class func initialize() {
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
convenience init(user: User, post: Post? = nil, reason: ComplaintReason) {
self.init()
if let post = post {
suspectedPost = post
}
guard let complainer = User.currentUser() else {
log.debug("Nil current user")
return
}
self.complainer = complainer
self.complaintReason = NSLocalizedString(reason.rawValue, comment: "")
self.suspectedUser = user
}
func postQuery() -> PFQuery {
let query = PFQuery(className: Complaint.parseClassName())
query.cachePolicy = .NetworkElseCache
query.orderByDescending("updatedAt")
query.whereKey("complainer", equalTo: complainer)
// query is called only when suspectedPost != nil
query.whereKey("suspectedPost", equalTo: suspectedPost!)
query.whereKey("suspectedUser", equalTo: suspectedUser)
return query
}
}
extension Complaint: PFSubclassing {
static func parseClassName() -> String {
return "Complaint"
}
}
| mit | aa7064e49bcc30d8c509452ecd61c924 | 24.491803 | 78 | 0.630868 | 4.248634 | false | false | false | false |
benlangmuir/swift | test/SILGen/auto_generated_super_init_call.swift | 7 | 5982 | // RUN: %target-swift-emit-silgen -Xllvm -sil-print-debuginfo %s | %FileCheck %s
// Test that we emit a call to super.init at the end of the initializer, when none has been previously added.
class Parent {
init() {}
}
class SomeDerivedClass : Parent {
var y: Int
func foo() {}
override init() {
y = 42
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SomeDerivedClass) -> @owned SomeDerivedClass
// CHECK: integer_literal $Builtin.IntLiteral, 42
// CHECK: [[SELFLOAD:%[0-9]+]] = load [take] [[SELF:%[0-9]+]] : $*SomeDerivedClass
// CHECK-NEXT: [[PARENT:%[0-9]+]] = upcast [[SELFLOAD]] : $SomeDerivedClass to $Parent
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[INITCALL1:%[0-9]+]] = function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent
// CHECK-NEXT: [[RES1:%[0-9]+]] = apply [[INITCALL1]]([[PARENT]])
// CHECK-NEXT: [[DOWNCAST:%[0-9]+]] = unchecked_ref_cast [[RES1]] : $Parent to $SomeDerivedClass
// CHECK-NEXT: store [[DOWNCAST]] to [init] [[SELF]] : $*SomeDerivedClass
}
init(x: Int) {
y = x
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass
// CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent
}
init(b: Bool) {
if b {
y = 0
return
} else {
y = 10
}
return
// Check that we are emitting the super.init expr into the epilog block.
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Bool, @owned SomeDerivedClass) -> @owned SomeDerivedClass
// CHECK: bb5:
// SEMANTIC ARC TODO: Another case of needing a mutable load_borrow.
// CHECK-NEXT: [[SELFLOAD:%[0-9]+]] = load [take] [[SELF:%[0-9]+]] : $*SomeDerivedClass
// CHECK-NEXT: [[SELFLOAD_PARENT_CAST:%.*]] = upcast [[SELFLOAD]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[PARENT_INIT:%.*]] = function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent,
// CHECK-NEXT: [[PARENT:%.*]] = apply [[PARENT_INIT]]([[SELFLOAD_PARENT_CAST]])
// CHECK-NEXT: [[SELFAGAIN:%.*]] = unchecked_ref_cast [[PARENT]]
// CHECK-NEXT: store [[SELFAGAIN]] to [init] [[SELF]]
// CHECK-NEXT: [[SELFLOAD:%.*]] = load [copy] [[SELF]]
// CHECK-NEXT: end_borrow
// CHECK-NEXT: destroy_value
// CHECK-NEXT: return [[SELFLOAD]]
}
// CHECK: } // end sil function '$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc'
// One init has a call to super init. Make sure we don't insert more than one.
init(b: Bool, i: Int) {
if (b) {
y = i
} else {
y = 0
}
super.init()
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call16SomeDerivedClassC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (Bool, Int, @owned SomeDerivedClass) -> @owned SomeDerivedClass
// CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent
// CHECK: return
}
}
// Check that we do call super.init.
class HasNoIVars : Parent {
override init() {
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call10HasNoIVarsC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned HasNoIVars) -> @owned HasNoIVars
// CHECK: function_ref @$s30auto_generated_super_init_call6ParentCACycfc : $@convention(method) (@owned Parent) -> @owned Parent
}
}
// Check that we don't call super.init.
class ParentLess {
var y: Int
init() {
y = 0
}
}
class Grandparent {
init() {}
}
// This should have auto-generated default initializer.
class ParentWithNoExplicitInit : Grandparent {
}
// Check that we add a call to super.init.
class ChildOfParentWithNoExplicitInit : ParentWithNoExplicitInit {
var y: Int
override init() {
y = 10
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call31ChildOfParentWithNoExplicitInitC{{[_0-9a-zA-Z]*}}fc
// CHECK: function_ref @$s30auto_generated_super_init_call24ParentWithNoExplicitInitCACycfc : $@convention(method) (@owned ParentWithNoExplicitInit) -> @owned ParentWithNoExplicitInit
}
}
// This should have auto-generated default initializer.
class ParentWithNoExplicitInit2 : Grandparent {
var i: Int = 0
}
// Check that we add a call to super.init.
class ChildOfParentWithNoExplicitInit2 : ParentWithNoExplicitInit2 {
var y: Int
override init() {
y = 10
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call32ChildOfParentWithNoExplicitInit2C{{[_0-9a-zA-Z]*}}fc
// CHECK: function_ref @$s30auto_generated_super_init_call25ParentWithNoExplicitInit2CACycfc : $@convention(method) (@owned ParentWithNoExplicitInit2) -> @owned ParentWithNoExplicitInit2
}
}
// Do not insert the call nor warn - the user should call init(5).
class ParentWithNoDefaultInit {
var i: Int
init(x: Int) {
i = x
}
}
class ChildOfParentWithNoDefaultInit : ParentWithNoDefaultInit {
var y: Int
init() {
// CHECK-LABEL: sil hidden [ossa] @$s30auto_generated_super_init_call30ChildOfParentWithNoDefaultInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned ChildOfParentWithNoDefaultInit) -> @owned ChildOfParentWithNoDefaultInit
// CHECK: bb0
// CHECK-NOT: apply
// CHECK: return
}
}
// <https://bugs.swift.org/browse/SR-5974> - auto-generated super.init()
// delegation to a throwing or failing initializer
class FailingParent {
init?() {}
}
class ThrowingParent {
init() throws {}
}
class FailingThrowingParent {
init?() throws {}
}
class FailingChild : FailingParent {
override init?() {}
}
class ThrowingChild : ThrowingParent {
override init() throws {}
}
class FailingThrowingChild : FailingThrowingParent {
override init?() throws {}
}
| apache-2.0 | 3eb92e6549aa607afe6a9b9b803ba70e | 36.15528 | 225 | 0.687396 | 3.416334 | false | false | false | false |
MKGitHub/UIPheonix | Demo/iOS/DemoCollectionViewController.swift | 1 | 11386 | /**
UIPheonix
Copyright © 2016/2017/2018/2019 Mohsan Khan. All rights reserved.
https://github.com/MKGitHub/UIPheonix
http://www.xybernic.com
Copyright 2016/2017/2018/2019 Mohsan Khan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
final class DemoCollectionViewController:UIPBaseViewController, UIPButtonDelegate,
UICollectionViewDataSource, /*UICollectionViewDataSourcePrefetching,*/ UICollectionViewDelegateFlowLayout
{
// MARK: Public Inner Struct
struct AttributeKeyName
{
static let appDisplayState = "AppDisplayState"
}
// MARK: Public IB Outlet
@IBOutlet private weak var ibCollectionView:UICollectionView!
// MARK: Private Members
private var mAppDisplayStateType:AppDisplayStateType!
private var mUIPheonix:UIPheonix!
// (for demo purpose only)
private var mPersistentDisplayModels:Array<UIPBaseCellModelProtocol>?
// MARK:- Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
// init member
mAppDisplayStateType = (newInstanceAttributes[AttributeKeyName.appDisplayState] as! AppDisplayState).value
initUIPheonix()
setupCollectionView()
updateView()
}
// MARK:- UICollectionViewDataSource
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
return mUIPheonix.displayModelsCount(forSection:0)
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
return mUIPheonix.collectionViewCell(forIndexPath:indexPath)
}
// MARK:- UICollectionViewDataSourcePrefetching
/**
Not used in this example.
*/
/*@available(iOS 10.0, *)
func collectionView(_ collectionView:UICollectionView, prefetchItemsAt indexPaths:[IndexPath])
{
// empty for now
}*/
// MARK:- UICollectionViewDelegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets
{
return UIEdgeInsets(top:10, left:0, bottom:10, right:0)
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, minimumLineSpacingForSectionAt section:Int) -> CGFloat
{
return 10
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
return mUIPheonix.collectionViewCellSize(forIndexPath:indexPath)
}
// MARK:- UIPButtonDelegate
func handleAction(forButtonId buttonId:Int)
{
var isTheAppendModelsDemo:Bool = false
var isThePersistentModelsDemo:Bool = false
var isTheCustomMadeModelsDemo:Bool = false
var shouldAnimateChange:Bool = true
// set the display state depending on which button we clicked
switch (buttonId)
{
case ButtonId.startUp.rawValue: mAppDisplayStateType = AppDisplayState.startUp.value; break
case ButtonId.mixed.rawValue: mAppDisplayStateType = AppDisplayState.mixed.value; break
case ButtonId.animations.rawValue: mAppDisplayStateType = AppDisplayState.animations.value; break
case ButtonId.switching.rawValue: mAppDisplayStateType = AppDisplayState.switching.value; break
case ButtonId.appending.rawValue: mAppDisplayStateType = AppDisplayState.appending.value; break
case ButtonId.appendingReload.rawValue:
mAppDisplayStateType = AppDisplayState.appending.value
isTheAppendModelsDemo = true
shouldAnimateChange = false
break
case ButtonId.persistent.rawValue:
mAppDisplayStateType = AppDisplayState.persistent.value
isThePersistentModelsDemo = true
break
case ButtonId.persistentGoBack.rawValue:
mAppDisplayStateType = AppDisplayState.startUp.value
// when we leave the state, store the current display models for later reuse
// so that when we re-enter the state, we can just use them as they were
mPersistentDisplayModels = mUIPheonix.displayModels(forSection:0)
break
case ButtonId.specific.rawValue: mAppDisplayStateType = AppDisplayState.specific.value; break
case ButtonId.customMadeModels.rawValue:
mAppDisplayStateType = AppDisplayState.customMadeModels.value;
isTheCustomMadeModelsDemo = true
break
default: mAppDisplayStateType = AppDisplayState.startUp.value; break
}
// update UI
if (shouldAnimateChange)
{
animateView(animationState:false, completionHandler:
{
[weak self] in
guard let self = self else { fatalError("DemoCollectionViewController buttonAction: `self` does not exist anymore!") }
self.updateView(isTheAppendModelsDemo:isTheAppendModelsDemo,
isThePersistentDemo:isThePersistentModelsDemo,
isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo)
self.animateView(animationState:true, completionHandler:nil)
})
}
else
{
updateView(isTheAppendModelsDemo:isTheAppendModelsDemo,
isThePersistentDemo:isThePersistentModelsDemo,
isTheCustomMadeModelsDemo:isTheCustomMadeModelsDemo)
}
}
// MARK:- Private
private func initUIPheonix()
{
mUIPheonix = UIPheonix(collectionView:ibCollectionView, delegate:self)
}
private func setupCollectionView()
{
/**
Does not seem to work, bug reported to Apple.
*/
/*if #available(iOS 10.0, *)
{
(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
//(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50)
}
else
{
// fallback on earlier versions
(ibCollectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width:ibCollectionView.bounds.width, height:50)
}*/
ibCollectionView.delegate = self
ibCollectionView.dataSource = self
/**
Not used in this example.
*/
/*if #available(iOS 10.0, *)
{
ibCollectionView.prefetchDataSource = self
// ibCollectionView.isPrefetchingEnabled, true by default
}
else {
// fallback on earlier versions
}*/
}
private func setupWithJSON()
{
if let jsonDictionary = DataProvider.loadJSON(inFilePath:mAppDisplayStateType.jsonFileName.rawValue)
{
mUIPheonix.setModelViewRelationships(withDictionary:jsonDictionary[UIPConstants.Collection.modelViewRelationships] as! Dictionary<String, String>)
mUIPheonix.setDisplayModels(jsonDictionary[UIPConstants.Collection.cellModels] as! Array<Any>, forSection:0, append:false)
}
else
{
fatalError("DemoCollectionViewController setupWithJSON: Failed to init with JSON file!")
}
}
private func setupWithModels()
{
mUIPheonix.setModelViewRelationships(withDictionary:[SimpleButtonModel.nameOfClass:SimpleButtonModelCVCell.nameOfClass,
SimpleCounterModel.nameOfClass:SimpleCounterModelCVCell.nameOfClass,
SimpleLabelModel.nameOfClass:SimpleLabelModelCVCell.nameOfClass,
SimpleTextFieldModel.nameOfClass:SimpleTextFieldModelCVCell.nameOfClass,
SimpleVerticalSpaceModel.nameOfClass:SimpleVerticalSpaceModelCVCell.nameOfClass,
SimpleViewAnimationModel.nameOfClass:SimpleViewAnimationModelCVCell.nameOfClass])
var models = [UIPBaseCellModel]()
for i in 1 ... 20
{
let simpleLabelModel = SimpleLabelModel(text:" Label \(i)",
size:(12.0 + CGFloat(i) * 2.0),
alignment:SimpleLabelModel.Alignment.left,
style:SimpleLabelModel.Style.regular,
backgroundColorHue:(CGFloat(i) * 0.05),
notificationId:"")
models.append(simpleLabelModel)
}
let simpleButtonModel = SimpleButtonModel(id:ButtonId.startUp.rawValue, title:"Enough with the RAINBOW!")
models.append(simpleButtonModel)
mUIPheonix.setDisplayModels(models, forSection:0)
}
private func updateView(isTheAppendModelsDemo:Bool=false, isThePersistentDemo:Bool=false, isTheCustomMadeModelsDemo:Bool=false)
{
if (isTheAppendModelsDemo)
{
// append the current display models list to itself
mUIPheonix.addDisplayModels(mUIPheonix.displayModels(forSection:0), inSection:0)
}
else if (isThePersistentDemo)
{
if (mPersistentDisplayModels == nil) {
setupWithJSON()
}
else
{
// set the persistent display models
mUIPheonix!.setDisplayModels(mPersistentDisplayModels!, forSection:0)
}
}
else if (isTheCustomMadeModelsDemo)
{
setupWithModels()
}
else
{
setupWithJSON()
}
// reload the collection view
ibCollectionView.reloadData()
}
private func animateView(animationState:Bool, completionHandler:(()->Void)?)
{
// do a nice fading animation
UIView.animate(withDuration:0.25, animations:
{
[weak self] in
guard let self = self else { fatalError("DemoCollectionViewController animateView: `self` does not exist anymore!") }
self.ibCollectionView.alpha = animationState ? 1.0 : 0.0
},
completion:
{
(animationCompleted:Bool) in
completionHandler?()
})
}
}
| apache-2.0 | 8e4d4364e8d89130f94f1f3fa4da91d5 | 34.357143 | 165 | 0.633289 | 5.661363 | false | false | false | false |
slavapestov/swift | test/SILGen/dynamic_lookup.swift | 1 | 11963 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -disable-objc-attr-requires-foundation-module %s | FileCheck %s
// REQUIRES: objc_interop
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup15direct_to_class
func direct_to_class(obj: AnyObject) {
// CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
obj.f!()
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup18direct_to_protocol
func direct_to_protocol(obj: AnyObject) {
// CHECK: [[OBJ_SELF:%[0-9]+]] = open_existential_ref [[EX:%[0-9]+]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #P.g!1.foreign : <Self where Self : P> Self -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
obj.g!()
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup23direct_to_static_method
func direct_to_static_method(obj: AnyObject) {
var obj = obj
// CHECK: [[START:[A-Za-z0-9_]+]]([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = dynamic_method [volatile] [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!1.foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
obj.dynamicType.staticF!()
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup12opt_to_class
func opt_to_class(obj: AnyObject) {
var obj = obj
// CHECK: [[ENTRY:[A-Za-z0-9]+]]([[PARAM:%[0-9]+]] : $AnyObject)
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: store [[PARAM]] to [[PBOBJ]]
// CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK-NEXT: [[EXISTVAL:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: strong_retain [[EXISTVAL]] : $AnyObject
// CHECK-NEXT: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXIST:%[0-9]+]]
// CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!1.foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK-NEXT: strong_retain [[OBJ_SELF]]
// CHECK-NEXT: [[PARTIAL:%[0-9]+]] = partial_apply [[UNCURRIED]]([[OBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK-NEXT: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPTIONAL:%[0-9]+]]
// CHECK: [[THUNKFN:%.*]] = function_ref @{{.*}} : $@convention(thin) (@out (), @in (), @owned @callee_owned () -> ()) -> ()
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNKFN]]([[PARTIAL]])
// CHECK-NEXT: store [[THUNK]] to [[THUNK_PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}Some
// CHECK-NEXT: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK-NEXT: inject_enum_addr [[OPTIONAL]]{{.*}}None
// CHECK-NEXT: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK-NEXT: [[OPT:%.*]] = load [[OPTTEMP]]
// CHECK-NEXT: store [[OPT]] to [[PBOPT]] : $*ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: dealloc_stack [[OPTTEMP]]
var of = obj.f
// Exit
// CHECK-NEXT: strong_release [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK-NEXT: strong_release [[OPTBOX]] : $@box ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: strong_release [[EXISTBOX]] : $@box AnyObject
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup20forced_without_outer
func forced_without_outer(obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup20opt_to_static_method
func opt_to_static_method(obj: AnyObject) {
var obj = obj
// CHECK: [[ENTRY:[A-Za-z0-9]+]]([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OPTBOX:%[0-9]+]] = alloc_box $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK-NEXT: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<() -> ()>
// CHECK-NEXT: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!1.foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF = obj.dynamicType.staticF
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup15opt_to_property
func opt_to_property(obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[INT_BOX:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: project_box [[INT_BOX]]
// CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int>
// CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject
// CHECK-NEXT: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int>
// CHECK-NEXT: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.1.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK-NEXT: strong_retain [[RAWOBJ_SELF]]
// CHECK-NEXT: [[BOUND_METHOD:%[0-9]+]] = partial_apply [[METHOD]]([[RAWOBJ_SELF]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[BOUND_METHOD]]() : $@callee_owned () -> Int
// CHECK-NEXT: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK-NEXT: store [[VALUE]] to [[VALUETEMP]]
// CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}Some
// CHECK-NEXT: br bb3
var i: Int = obj.value!
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup19direct_to_subscript
func direct_to_subscript(obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK-NEXT: store [[I]] to [[PBI]] : $*Int
// CHECK-NEXT: alloc_box $Int
// CHECK-NEXT: project_box
// CHECK-NEXT: [[UNKNOWN_USE:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int>
// CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject
// CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int
// CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int>
// CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK-NEXT: strong_retain [[OBJ_REF]]
// CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int
// CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]]
// CHECK-NEXT: inject_enum_addr [[OPTTEMP]]{{.*}}Some
// CHECK-NEXT: br bb3
var x: Int = obj[i]!
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup16opt_to_subscript
func opt_to_subscript(obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[I_BOX:%[0-9]+]] = alloc_box $Int
// CHECK-NEXT: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK-NEXT: store [[I]] to [[PBI]] : $*Int
// CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject
// CHECK-NEXT: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK-NEXT: [[I:%[0-9]+]] = load [[PBI]] : $*Int
// CHECK-NEXT: [[OPTTEMP:%.*]] = alloc_stack $ImplicitlyUnwrappedOptional<Int>
// CHECK-NEXT: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.1.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK-NEXT: strong_retain [[OBJ_REF]]
// CHECK-NEXT: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [[GETTER]]([[OBJ_REF]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[GETTER_WITH_SELF]]([[I]]) : $@callee_owned (Int) -> Int
// CHECK-NEXT: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK-NEXT: store [[RESULT]] to [[RESULTTEMP]]
// CHECK-NEXT: inject_enum_addr [[OPTTEMP]]
// CHECK-NEXT: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden @_TF14dynamic_lookup8downcast
func downcast(obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box $AnyObject
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: store [[OBJ]] to [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: [[OBJ:%[0-9]+]] = load [[PBOBJ]] : $*AnyObject
// CHECK-NEXT: strong_retain [[OBJ]] : $AnyObject
// CHECK-NEXT: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to $X
// CHECK-NEXT: strong_release [[OBJ_BOX]] : $@box AnyObject
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: return [[X]] : $X
return obj as! X
}
| apache-2.0 | 5c84da8c5d3de715f61cf7ffee73f871 | 51.700441 | 243 | 0.586057 | 3.243764 | false | false | false | false |
WildenChen/LionEvents | LionEvents/LionEvents/LNButton.swift | 1 | 4019 | //
// LNButton.swift
// LionActions
//
// Created by wilden on 2015/6/12.
// Copyright (c) 2015年 Lion Infomation Technology Co.,Ltd. All rights reserved.
//
import UIKit
public typealias LNButtonEvents = LNTouchEvents
open class LNButton: UIButton {
private var mIsTouchInside:Bool = true
override open var isTouchInside:Bool{
set(value){
if mIsTouchInside != value {
mIsTouchInside = value
if mIsTouchInside {
let _event:Event = Event(aType: LNButtonEvents.TOUCH_ROLL_OVER.rawValue, aBubbles: true)
dispatchEvent(_event)
}else{
let _event:Event = Event(aType: LNButtonEvents.TOUCH_ROLL_OUT.rawValue, aBubbles: true)
dispatchEvent(_event)
}
}
}
get{
return mIsTouchInside
}
}
public init(){
super.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let _event:Event = Event(aType: LNButtonEvents.TOUCH_DOWN.rawValue, aBubbles: true)
self.dispatchEvent(_event)
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
let _touch:UITouch = touches.first!
let _touchendPoint:CGPoint = _touch.location(in: self)
if _touchendPoint.x < 0 || _touchendPoint.x > self.bounds.width || _touchendPoint.y < 0 || _touchendPoint.y > self.bounds.height {
let _event:Event = Event(aType: LNButtonEvents.TOUCH_UP_OUTSIDE.rawValue, aBubbles: true)
dispatchEvent(_event)
}else {
let _event:Event = Event(aType: LNButtonEvents.TOUCH_UP_INSIDE.rawValue, aBubbles: true)
dispatchEvent(_event)
}
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
let _touch:UITouch = touches.first!
let _touchendPoint:CGPoint = _touch.location(in: self)
let _event:Event = Event(aType: LNButtonEvents.TOUCH_MOVE.rawValue, aBubbles: true)
dispatchEvent(_event)
if _touchendPoint.x < 0 || _touchendPoint.x > self.bounds.width || _touchendPoint.y < 0 || _touchendPoint.y > self.bounds.height {
self.isTouchInside = false
}else{
self.isTouchInside = true
}
}
override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
let _event:Event = Event(aType: LNButtonEvents.TOUCH_CANCEL.rawValue, aBubbles: true)
dispatchEvent(_event)
}
@discardableResult open func addEventListener(_ aEventType: LNButtonEvents, _ aHandler:@escaping () -> Void) -> EventListener {
return self.addEventListener(aEventType.rawValue, aHandler)
}
@discardableResult open func addEventListener(_ aEventType: LNButtonEvents, _ aHandler:@escaping (_ aEvent: Event) -> Void) -> EventListener {
return self.addEventListener(aEventType.rawValue, aHandler)
}
open func removeEventListener(_ aEventType: LNButtonEvents){
self.removeEventListener(aEventType.rawValue)
}
open func removeEventListener(_ aEventType:LNButtonEvents, aListener:EventListener){
let _eventType:String = aEventType.rawValue
self.removeEventListener(_eventType, aListener)
if !hasEventListener(_eventType) {
self.removeEventListener(_eventType)
}
}
open func removeAllEventListener(){
self.removeEventListener(nil)
}
}
| bsd-3-clause | 99af5b9b0cb53954d2bb61f05dc8a17e | 36.542056 | 146 | 0.631068 | 4.300857 | false | false | false | false |
slavapestov/swift | test/DebugInfo/generic_args.swift | 4 | 2096 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -verify -g -o - | FileCheck %s
func markUsed<T>(t: T) {}
protocol AProtocol {
func f() -> String
}
class AClass : AProtocol {
func f() -> String { return "A" }
}
class AnotherClass : AProtocol {
func f() -> String { return "B" }
}
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}",{{.*}} elements: ![[PROTOS:[0-9]+]]
// CHECK-DAG: ![[PROTOS]] = !{![[INHERIT:.*]]}
// CHECK-DAG: ![[INHERIT]] = !DIDerivedType(tag: DW_TAG_inheritance,{{.*}} baseType: ![[PROTOCOL:"[^"]+"]]
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtMP12generic_args9AProtocol_",{{.*}} identifier: [[PROTOCOL]]
// CHECK-DAG: !DILocalVariable(name: "x", arg: 1,{{.*}} type: ![[T:.*]])
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq_F12generic_args9aFunction{{.*}}, identifier: [[T]])
// CHECK-DAG: !DILocalVariable(name: "y", arg: 2,{{.*}} type: ![[Q:.*]])
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "_TtQq0_F12generic_args9aFunction{{.*}}, identifier: [[Q]])
func aFunction<T : AProtocol, Q : AProtocol>(x: T, _ y: Q, _ z: String) {
markUsed("I am in \(z): \(x.f()) \(y.f())")
}
aFunction(AClass(),AnotherClass(),"aFunction")
struct Wrapper<T: AProtocol> {
init<U: AProtocol>(from : Wrapper<U>) {
// CHECK-DAG: !DICompositeType(tag: DW_TAG_structure_type, name: "Wrapper",{{.*}} identifier: "_TtGV12generic_args7WrapperQq_FS0_cuRd__S_9AProtocolrFT4fromGS0_qd____GS0_x__")
var wrapped = from
wrapped = from
_ = wrapped
}
func passthrough(t: T) -> T {
// The type of local should have the context Wrapper<T>.
// CHECK-DAG: !DILocalVariable(name: "local",{{.*}} line: [[@LINE+1]],{{.*}} type: !"_TtQq_V12generic_args7Wrapper"
var local = t
local = t
return local
}
}
// CHECK: !DILocalVariable(name: "f", {{.*}}, line: [[@LINE+1]], type: !"_TtFQq_F12generic_args5applyu0_rFTx1fFxq__q_Qq0_F12generic_args5applyu0_rFTx1fFxq__q_")
func apply<T, U> (x: T, f: (T) -> (U)) -> U {
return f(x)
}
| apache-2.0 | 7069247900bba8f100c9c896444a65c9 | 40.098039 | 176 | 0.619752 | 2.977273 | false | false | false | false |
furqanmk/github | microapps-testapplication/IssueTableViewCell.swift | 1 | 627 | //
// IssueTableViewCell.swift
// microapps-testapplication
//
// Created by Furqan on 26/12/2015.
// Copyright © 2015 Furqan Khan. All rights reserved.
//
import UIKit
class IssueTableViewCell: UITableViewCell {
@IBOutlet weak var issueTitle: UILabel!
@IBOutlet weak var issueBody: UILabel!
@IBOutlet weak var issueState: UILabel!
@IBOutlet weak var issueNumber: UILabel!
func setupIssue(issue: Issue) {
issueTitle.text = issue.title
issueBody.text = issue.body
issueState.text = issue.state == .Open ? "open": "closed"
issueNumber.text = "#\(issue.number)"
}
}
| mit | 5431f998833b3c995e92f911a48d2611 | 26.217391 | 65 | 0.675719 | 3.793939 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.