Swift set content compression resistance - ios

Using Swift again, am I missing something?
I have this line:
self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: UILayoutConstraintAxis.Vertical);
But Xcode is giving me an error:
Undefined symbols for architecture i386: "_UILayoutPriorityRequired"
Another one of Swift's quirks?

Solution: replace UILayoutPriorityRequired with 1000
self.itemDescription?.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Vertical);
This is not a bug. It is a misunderstanding of how Objective-C libraries are imported into Swift. It should be understood how Swift imports code (even from the Apple UIKIt Libraries) from Objective-C into Swift.
UILayoutPriority is a float. In Objective-C, a couple of values have been pre-defined for us. The pre-defined values appear to be an enum. We might expect that the same enums would be available to us in Swift.
The documentation does seem to imply an enum:
SWIFT (Documentation)
typealias UILayoutPriority = Float
OBJECTIVE-C (Documentation)
enum {
UILayoutPriorityRequired = 1000,
UILayoutPriorityDefaultHigh = 750,
UILayoutPriorityDefaultLow = 250,
UILayoutPriorityFittingSizeLevel = 50,
};
typedef float UILayoutPriority;
But in Xcode, if you ask to see the defintion of one of these enum values (UILayoutPriorityRequired, for example), you will see that they are actually defined in the header file as constant floats.
OBJECTIVE-C (Header file)
typedef float UILayoutPriority;
static const UILayoutPriority UILayoutPriorityRequired NS_AVAILABLE_IOS(6_0) = 1000; // A required constraint. Do not exceed this.
static const UILayoutPriority UILayoutPriorityDefaultHigh NS_AVAILABLE_IOS(6_0) = 750; // This is the priority level with which a button resists compressing its content.
static const UILayoutPriority UILayoutPriorityDefaultLow NS_AVAILABLE_IOS(6_0) = 250; // This is the priority level at which a button hugs its contents horizontally.
So although we may like to think of the pre-defined layout priorities as enum values (as the documentation suggests) the layout priorities are not really defined as enums; they are defined as constant floats.
A hint that there is a mis-match -- for anyone that knows the C programming language -- is that a C enum may only contain int values. The following is legal and will compile:
enum myEnum {
JGCEnum_one = 1, // this is O.K.
JGCEnum_two,
JGCEnum_three
} JGCEnum;
But we can not define floats as values for C enums. The following will not compile:
enum myEnum {
JGCEnum_one = 1.5, // compile error
JGCEnum_two,
JGCEnum_three
} JGCEnum;
Objective-C enums are the same as C enums (Swift enums are different). It is important to know if we are dealing with actual integers or floats. Because integers can be defined using the NS_ENUM macro, which can then be imported to Swift as a Swift enum.
The iBook says
Swift imports as a Swift enumeration any C-style enumeration marked with the NS_ENUM macro. This means that the prefixes to enumeration value names are truncated when they are imported into Swift, whether they’re defined in system frameworks or in custom code.
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks
That means that if UILayoutPriority had been defined as an integer using the NS_ENUM macro, it would have been imported into Swift as Swift enum. This is the case for UILayoutConstraintAxis.
SWIFT (Documentation)
enum UILayoutConstraintAxis : Int {
case Horizontal
case Vertical
}
OBJECTIVE-C (Documentation)
enum {
UILayoutConstraintAxisHorizontal = 0,
UILayoutConstraintAxisVertical = 1
};
typedef NSInteger UILayoutConstraintAxis;
Looking at the Objective-C header file confirms what the documentation says.
OBJECTIVE-C (Header File)
//
// UIView Constraint-based Layout Support
//
typedef NS_ENUM(NSInteger, UILayoutConstraintAxis) {
UILayoutConstraintAxisHorizontal = 0,
UILayoutConstraintAxisVertical = 1
};
So there are at least two ways to know if a pre-defined value you are used to using in Objective-C is available in Swift:
check the documentation
check the header file in Objective-C (found by right-clicking the value and then selecting "Jump to Definition")
There is one more way to see if a typedef you are used to using is a constant or an enum. In code, test to see if the address of the constant exists. Constants have a memory address, while enums do not. See the code below.
// this line will compile and run just fine.
// UILayoutPriorityDefaultHigh is a constant and has a memory address
// the value will be true if the device is running iOS 6.0 or later
// and false otherwise
BOOL predefinedValueIsAvailable = (NULL != &UILayoutPriorityDefaultHigh);
// this line will not compile
// UILayoutConstraintAxisHorizontal is an enum (NOT a constant)
// and does not have a memory address
predefinedValueIsAvailable = (NULL != &UILayoutConstraintAxisHorizontal);
References
Using Layout Priority in Swift
Xcode Documentation (iOS 8.2)
Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks

One thing to keep in mind is that, even though UILayoutPriority is an alias to Float, you're using Swift and you can use an extension to create semantic constants for these values:
extension UILayoutPriority {
static var Low: Float { return 250.0 }
static var High: Float { return 750.0 }
static var Required: Float { return 1000.0 }
}
Then you're code can read as:
self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority.Required, forAxis: .Vertical);
I've done this myself in one of my projects and thought it may be useful.

You can also write this:
self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(<float number>), forAxis: .Vertical)
Example:
self.itemDescription?.setContentCompressionResistancePriority(UILayoutPriority(750), forAxis: .Vertical)

Related

What's the Enum value difference between 'k' and 'v' in Swift?

I just updated the latest Xcode today, when I build my project, the project was occurred an error.
Like this:
let playerStatus: BJYPlayerStatus = .playing // ambiguous use of 'playing'
The enum defined like this:
typedef NS_ENUM (NSInteger, BJVPlayerStatus) {
BJVPlayerStatus_playing,
// other cases...
BJVPlayerStatus_Playing DEPRECATED_MSG_ATTRIBUTE("use `BJVPlayerStatus_playing`") =
BJVPlayerStatus_playing
// other deprecated cases...
};
It is ambiguous about the 'playing'.
I don't know how to write to distinguish both of the '.playing'.
Thanks for your answer!
First, to answer the question in the title. "K" means an enum case (they don't use "C" because it's used for "class" already). "V" means a var (or let), i.e. a property.
The Objective-C enum gets treated like this in Swift:
// This is not real Swift code, for illustrative purposes only
enum BJVPlayerStatus : Int {
// This was BJVPlayerStatus_playing
case playing
// ...
// This was BJVPlayerStatus_Playing
#available(*, deprecated, message: "use `BJVPlayerStatus_playing`")
var playing: BJVPlayerStatus {
return BJVPlayerStatus.playing // returns the *case* .playing
}
// ...
}
The point here is that the deprecated BJVPlayerStatus_Playing is treated as a computed property in Swift, rather than an enum case, hence the "V". This is because you wrote
BJVPlayerStatus_Playing = BJVPlayerStatus_playing
in your Objective-C code.
Anyway, both the uppercase and lowercase name translates to playing in Swift, and that causes the conflict. You need to either:
use separate header files for the Swift and Objective-C code, so the Swift code doesn't see the deprecated cases, or
rename the Swift name for the deprecated case to something else using NS_SWIFT_NAME.
BJVPlayerStatus_Playing NS_SWIFT_NAME(deprecatedPlaying) DEPRECATED_MSG_ATTRIBUTE("use `BJVPlayerStatus_playing`") =
BJVPlayerStatus_playing

Accessing NS_OPTIONS in swift option unavailable

I defined an NS_OPTIONS in Objective-C .h file:
typedef NS_OPTIONS (NSInteger, Options){
OptionsOne,
OptionsTwo,
OptionsThree
};
Now when accessing from Swift:
public func myFunc() -> Options {
return [.one, .two]
}
I am getting this error:
'one' is unavailable: use [] to construct an empty option set.
But I am not getting this error for .two or .three. It appears only for the first option.
By default, in Swift 3, an NS_OPTIONS enumerand equating to 0 is not imported into Swift by name. You have to use [] in Swift to get it.
When you changed the enumerand's value to 1, the name was imported.
If you think about it, this makes perfect sense. NS_OPTIONS is for bitmasks. Thus, if (let's say) .one is 0 and .two is 1, there is no useful meaning to the expression [.one, .two] because there is no information added by the presence of the .one.
What you were doing, on the other hand, was always a misuse of NS_OPTIONS, since it was not a bitmask. Your modification turned it into one. (Objective-C does not magically generate bitmask-appropriate values for you.)
I have found the solution to this to be adding explicit bitmask value to the options:
typedef NS_OPTIONS (NSInteger, Options){
OptionsOne = 1 << 0,
OptionsTwo = 1 << 1,
OptionsThree = = 1 << 2
};
and the error went away.

Hash Define in objective C and usage in swift [duplicate]

I am migrating a UIViewController class to train a bit with Swift. I am successfully using Objective-C code via the bridging header but I have the need of importing a constants file that contains #define directives.
I have seen in Using Swift with Cocoa and Objective-C (Simple macros) the following:
Simple Macros
Where you typically used the #define directive to define a primitive constant in C and Objective-C, in Swift you use a global constant instead. For example, the constant definition #define FADE_ANIMATION_DURATION 0.35 can be better expressed in Swift with let FADE_ANIMATION_DURATION = 0.35. Because simple constant-like macros map directly to Swift global variables, the compiler automatically imports simple macros defined in C and Objective-C source files.
So, it seems it's possible. I have imported the file containing my constants into the bridging header, but I have no visibility from my .swift file, cannot be resolved.
What should I do to make my constants visible to Swift?
UPDATE:
It seems working with NSString constants, but not with booleans:
#define kSTRING_CONSTANT #"a_string_constant" // resolved from swift
#define kBOOL_CONSTANT YES // unresolved from swift
At the moment, some #defines are converted and some aren't. More specifically:
#define A 1
...becomes:
var A: CInt { get }
Or:
#define B #"b"
...becomes:
var B: String { get }
Unfortunately, YES and NO aren't recognized and converted on the fly by the Swift compiler.
I suggest you convert your #defines to actual constants, which is better than #defines anyway.
.h:
extern NSString* const kSTRING_CONSTANT;
extern const BOOL kBOOL_CONSTANT;
.m
NSString* const kSTRING_CONSTANT = #"a_string_constant";
const BOOL kBOOL_CONSTANT = YES;
And then Swift will see:
var kSTRING_CONSTANT: NSString!
var kBOOL_CONSTANT: ObjCBool
Another option would be to change your BOOL defines to
#define kBOOL_CONSTANT 1
Faster. But not as good as actual constants.
Just a quick clarification on a few things from above.
Swift Constant are expressed using the keywordlet
For Example:
let kStringConstant:String = "a_string_constant"
Also, only in a protocol definition can you use { get }, example:
protocol MyExampleProtocol {
var B:String { get }
}
In swift you can declare an enum, variable or function outside of any class or function and it will be available in all your classes (globally)(without the need to import a specific file).
import Foundation
import MapKit
let kStringConstant:String = "monitoredRegions"
class UserLocationData : NSObject {
class func getAllMonitoredRegions()->[String]{
defaults.dictionaryForKey(kStringConstant)
}
simple swift language don't need an macros
all #define directives.
will be let
and complex macros should convert to be func
The alternative for macro can be global variable . We can declare global variable outside the class and access those without using class. Please find example below
import Foundation
let BASE_URL = "www.google.com"
class test {
}

How to use Objective-C code with #define macros in Swift

I'm trying to use a third-party Objective-C library in a Swift project of mine. I have the library successfully imported into Xcode, and I've made a <Project>-Bridging-Header.h file that's allowing me to use my Objective-C classes in Swift.
I seem to be running into one issue however: the Objective-C code includes a Constants.h file with the macro #define AD_SIZE CGSizeMake(320, 50). Importing Constants.h into my <Project>-Bridging-Header.h doesn't result in a global constant AD_SIZE that my Swift app can use.
I did some research and saw that the Apple documentation here under "Complex Macros" says that
“In Swift, you can use functions and generics to achieve the same
results [as complex macros] without any compromises. Therefore, the
complex macros that are in C and Objective-C source files are not made
available to your Swift code.”
After reading that, I got it to work fine by specifying let AD_SIZE = CGSizeMake(320, 50) in Swift, but I want to maintain future compatibility with the library in the event that these values change without me knowing.
Is there an easy fix for this in Swift or my bridging header? If not, is there a way to replace the #define AD_SIZE CGSizeMake(320, 50) in Constants.h and keep things backwards-compatible with any existing Objective-C apps that use the old AD_SIZE macro?
What I did is to create a class method that returns the #define.
Example:
.h file:
#define AD_SIZE CGSizeMake(320, 50)
+ (CGSize)adSize;
.m file:
+ (CGSize)adSize { return AD_SIZE; }
And in Swift:
Since this is a class method you can now use it almost as you would the #define.
If you change your #define macro - it will be reflected in the new method you created
In Swift:
let size = YourClass.adSize()
I resolved this by replacing
#define AD_SIZE CGSizeMake(320, 50)
in the library's Constants.h with
extern CGSize const AD_SIZE;
and adding
CGSize const AD_SIZE = { .width = 320.0f, .height = 50.0f };
in the library's Constants.m file.
write your constants after Class declaration. like this...
class ForgotPasswrdViewController: UIViewController {
let IS_IPHONE5 = fabs(UIScreen.mainScreen().bounds.size.height-568) < 1;
let Tag_iamTxtf = 101

Passing a Difficulty level between controllers

I am looking for the best way to pass a Difficulty level between View Controllers.
At present I have this setup as a String. There are three options Easy/Medium/Hard, I know this is not the best way to do this so am looking for what would be the correct approach here.
At the moment I check the tag on the button and set a string value like below:
if (sender.tag == 10) {
self.turnDifficulty = #"Easy";
} else if (sender.tag == 20) {
self.turnDifficulty = #"Medium";
} else if (sender.tag == 30) {
self.turnDifficulty = #"Hard";
}
I then pass the value over in the prepareForSegue method. What is the alternate to this approach? Although there is no issue here and this works fine, it is not very clean working with strings here.
One alternative to working with strings in Objective-C (indeed, in C and C++ as well) us using an enumeration:
typedef enum Difficulty {
DIFFICULTY_EASY
, DIFFICULTY_MEDIUM
, DIFFICULTY_HARD
} Difficulty;
Declare this enum in a header included from all your view controllers, and use enumeration constants as if they were numeric constants. The language will ensure that the constants remain distinct, even when you choose to add more items to the enumeration.
When you declare a #property or a parameter of type Difficulty, do not use an asterisk, because enums are primitive types, not reference types. For example:
#property (nonatomic, readwrite) Difficulty difficultyLevel;
or
-(void)openWithDifficulty:(Difficulty)level;
EDIT : (thanks, Rob!)
As of Xcode 4.4, you might also use an explicit fixed underlying type, e.g.
typedef enum Difficulty : NSUInteger {
kDifficultyEasy
, kDifficultyMedium
, kDifficultyHard
} Difficulty;
If your problem is just working with string you should declare an enumeration.
Write in a Enum.h that will be imported by all your controllers :
typedef enum
{
EASY = 0,
MEDIUM,
HARD
} DIFFICULTY;
Just for someone-who-wouldn't-know-what-this-is' information, this declare a restrictive integer type that can have only 3 values : EASY (= 0), MEDIUM (= 1), HARD (= 2).
It will be far cleaner (and better for your memory management).

Resources